将数字传递给组件

Vit*_*lyB 31 javascript reactjs

我试图将一个数字传递给一个React组件,但它被解析为字符串(jsfiddle).如何让React了解我正在传递一个号码?我应该将字符串转换为组件中的数字吗?

var Rectangle = React.createClass({
   
    render: function() {

        return <div>
            <div>{this.props.intValue + 10}</div>
            <div>{this.props.stringValue + 10}</div>
        </div>;
    }
});
 
React.render(<Rectangle intValue="10" stringValue="Hello" />
    , document.getElementById('container'));
Run Code Online (Sandbox Code Playgroud)
<script src="https://facebook.github.io/react/js/jsfiddle-integration.js"></script>

<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>
Run Code Online (Sandbox Code Playgroud)

Vit*_*lyB 55

似乎在整数的情况下(实际上对于字符串)我应该{}像这样传递数字:

React.render(<Rectangle intValue={10} stringValue={"Hello"} />, document.getElementById('container'));

  • 你为什么要传递像```stringValue = {"Hello"}```而不是```stringValue ="Hello"```这样的字符串? (5认同)
  • 您可以使用字符串执行此操作,但为了保持一致性,您可以采用相同的方式 (2认同)

yay*_*aya 7

您可以使用:

<MyComponent param1={10} param2={20} />
Run Code Online (Sandbox Code Playgroud)

或者:

<MyComponent {...{param1: 10, param2: 20}} />
Run Code Online (Sandbox Code Playgroud)