【问题标题】:How to pass more than one argument in component function in React如何在 React 的组件函数中传递多个参数
【发布时间】:2016-09-20 18:14:03
【问题描述】:

如何在 React 的组件函数中传递多个参数

 function Ads(product_title, description) {
    return(
      <div className = "row" id="user-ads">
     <div className = "col-sm-6 col-md-5">
      <div className = "thumbnail">
      <img src = "img/img1.jpg" alt = "Generic placeholder thumbnail" />
      </div>
      <div className = "caption">
      <div className="border">
         <h3>{product_title.title}</h3>
         <p>{description.desc}</p>  
            <button className = "btn btn-primary" role = "button" data-toggle="modal" data-target="#view-detail">View Details
            </button>  
              </div>
                </div>
                  </div>
                    </div>
      );

}

ReactDOM.render(<Ads title="PlayStation 4" desc="Lorem ipsum jipsum Lorem ipsum jipsum"/>, document.getElementById('ads'));

上面的代码只取第一个参数的值

【问题讨论】:

    标签: javascript html reactjs jsx


    【解决方案1】:

    Stateless React 组件只接收一个参数,一个包含所有道具的对象:

    function Ads(props) {
      // access props.title
      //        props.desc
    
      // ...
    }
    

    如果你look at what the JSX is actually converted to

    // Before:
    <Ads title="PlayStation 4" desc="Lorem ipsum jipsum Lorem ipsum jipsum"/>
    // After:
    React.createElement(
      Ads,
      { title: "PlayStation 4", desc: "Lorem ipsum jipsum Lorem ipsum jipsum" }
    );
    

    一种常见的模式是使用destructuring 直接访问道具:

    function Ads({title, desc}) {
      // ...
    }
    

    【讨论】:

    • TypeError: product_title 未定义
    • 你必须在任何地方使用props.title 而不是 product_title。我认为这会很清楚。
    【解决方案2】:

    在您提供的示例中,product_title.desc 应该具有您要查找的值。当您调用 &lt;Ads title="PlayStation 4" desc="Lorem ipsum jipsum Lorem ipsum jipsum"/&gt; 时,titledesc 都将作为对象的属性传递给您的组件函数,因此两者都将在您的函数中以您指定的第一个参数的名称可用,其中你的情况是product_title

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 2021-04-29
      • 2018-12-16
      • 2015-09-13
      • 2019-06-04
      • 1970-01-01
      • 2017-07-03
      • 1970-01-01
      相关资源
      最近更新 更多