【问题标题】:Passing a number to a component将数字传递给组件
【发布时间】:2023-03-21 19:54:01
【问题描述】:

我正在尝试将一个数字传递给 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'));
<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>

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    似乎对于整数(实际上也适用于字符串),我应该像这样通过{} 传递数字:

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

    【讨论】:

    • 为什么必须传递stringValue={"Hello"} 之类的字符串而不是stringValue="Hello"
    • 你可以用字符串做任何一种方式,但为了保持一致性,你可以用同样的方式来做
    【解决方案2】:

    您可以使用:

    <MyComponent param1={10} param2={20} />
    

    或者:

    <MyComponent {...{param1: 10, param2: 20}} />
    

    【讨论】:

      猜你喜欢
      • 2020-08-05
      • 2018-12-26
      • 2019-09-04
      • 2019-01-31
      • 1970-01-01
      • 2016-06-16
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多