简体   繁体   中英

Is there any other way to add attributes to a component in React?

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Is there any way to add attributes to the Welcome function-component, other than by creating a separate line such as <Welcome name="Sara" /> ?

Using .map() you can render the elements of an array as:

function App() {
  const elements = ["Sara", "Cahal", "Edite"]

  return (
    <div>
      { elements.map((e, i) => <Welcome key={i} name={e} />) }
    </div>
  );
}

Additionally I suggest to read through the documentation of Rendering Elements and Lists and Keys .

This is not the standard way of defining props, but I quite like the syntax of using an object with the spread operator to define props if you have variables with the names of the props you want.

function App() {
  const elements = ['Sara', 'Cahal', 'Edite'];

  return (
    <div>
      {elements.map((name, key) => (
        <Welcome {...{ name, key }} />
      ))}
    </div>
  );
}

You can create an array with names and after loop through it:

const names = ["Sara", "Cahal", "Edite"];

return (
    <div>
        {names.map(name => <Welcome key={name} name={name} />)}
    </div>
)

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