简体   繁体   中英

How to pass more than one argument in component function in React

How to pass more than one argument in components function in 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'));

The code above only takes the value of first parameter

In the example you provided, product_title.desc should have the value you're looking for. When you're calling <Ads title="PlayStation 4" desc="Lorem ipsum jipsum Lorem ipsum jipsum"/> , both title and desc will be passed to your component function as properties of an object, so both will be available in your function with the name of the first param you specified, which in your case is product_title .

Stateless React components only receive a single argument, an object that contains all the props:

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

  // ...
}

Maybe that becomes more obvious if you 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" }
);

A common pattern is to use destructuring to get direct access to the props:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM