React - 用于将计算样式传递给 div 的语法



我对反应的语言很陌生。我似乎不断在":"上收到意外的令牌错误。在如下所示的 Box 组件中放置多个样式的语法到底是什么?除此之外,如何放置多个这些Box组件,每个组件的边距都发生了变化,并放在一个数组中,显示在网站上。

ncaught SyntaxError: /Inline Babel script: Unexpected token, expected "}" (51:73)
const Box = (props) => <div style={"margin-left" : props.spacing, "width" : props.width, "height" : props.height, "background-color" : props.color}></div>
|                                                                          
^

盒子组件需要多个子组件,例如左边距(我什至不确定我是否可以在 React 中使用它(等等。然后我有一个 for 循环,它不断将盒子组件添加到数组中,每个组件都有不同的边距,以便它最终真正在div 中显示一行不同的元素。

class StoryPage extends React.Component {
render(){
const Box = (props) => <div style={"margin-left" : props.spacing; "width" : props.width; "height" : props.height; "background-color" : props.color;}></div>
const val = 0
const boxArray = []
for(let i = 0; i < 10; i++){
val += 100
boxArray.push(<Box spacing = {val} width = "100px" height = "100px" color = "black" />)
}
return(
<div>
{boxArray}
</div>
)
}
}

我基本上期望发生的是显示框元素数组。但是,我真的不确定我应该如何做到这一点。

你的"将对象文字作为道具传递"语法是错误的——解释如下。


React 道具的传递方式如下:

  • 字符串文本

    <Component strProp='hello' />
    // or
    <Component strProp={'hello'} />
    
  • 变量

    <Component strProp={this.props.foo} />
    
  • 数组文字

    <Component arrProp={[1, 2, 3]} />
    
  • 对象文字

    <Component objProp={{foo: 'bar'}} />
    

看到双花括号了吗?需要一对来将任何作为 prop 传递的非字符串文本表达式括起来,另一对只是对象文本表示法的一部分。


相比之下,这:

<Component objProp={foo: 'bar'} /> // <- WRONG

不起作用,因为foo: 'bar'不是表达式。

雨果是对的。此外,您不希望为每个元素添加较大的左边距,左边距指定从边框到左侧元素的距离。https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model

您可以在所有div 上将属性显示设置为"内联",以将div 的布局从块更改为内联。或者只是什么都不做,它们仍然会显示。 https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flow_Layout

你的问题是这一行:

const Box = (props) => <div style={"margin-left" : props.spacing; "width" : props.width; "height" : props.height; "background-color" : props.color;}></div>

您提供了错误的style属性,您需要提供如下:

const Box = (props) => (
<div 
style={{
marginLeft: props.spacing, 
width: props.width, 
height: props.height, 
backgroundColor: props.color
}}
/>
);

请注意,style属性应包含双大括号,并应使用逗号分隔属性,

演示

注意:在 React 中,内联样式名称应该在camelCase中。

例如

  • margin-left应该是marginLeft.
  • background-color应该是backgroundColor.

最新更新