美文网首页
react属性展开{...props}

react属性展开{...props}

作者: hanxianshe_9530 | 来源:发表于2019-10-30 09:40 被阅读0次

属性展开

如果你已经有了一个 props 对象,你可以使用展开运算符 ...来在 JSX 中传递整个 props 对象。以下两个组件是等价的:

function App1() {
  return <Greeting firstName="Ben" lastName="Hector" />;
}

function App2() {
  const props = {firstName: 'Ben', lastName: 'Hector'};
  return <Greeting {...props} />;
}

你还可以选择只保留当前组件需要接收的 props,并使用展开运算符将其他 props 传递下去。

const Button = props => {
  const { kind, ...other } = props;
  const className = kind === "primary" ? "PrimaryButton" : "SecondaryButton";
  return <button className={className} {...other} />;
};

const App = () => {
  return (
    <div>
      <Button kind="primary" onClick={() => console.log("clicked!")}>
        Hello World!
      </Button>
    </div>
  );
};

在上述例子中,kind 的 prop 会被安全的保留,它将不会被传递给 DOM 中的 <button> 元素。 所有其他的 props 会通过 ...other 对象传递,使得这个组件的应用可以非常灵活。你可以看到它传递了一个 onClickchildren 属性。

属性展开在某些情况下很有用,但是也很容易将不必要的 props 传递给不相关的组件,或者将无效的 HTML 属性传递给 DOM。我们建议谨慎的使用该语法。

JSX 中的子元素

在开始和结束标签之间的 JSX 表达式,将作为特定属性 props.children 传递给外层组件。

相关文章

网友评论

      本文标题:react属性展开{...props}

      本文链接:https://www.haomeiwen.com/subject/dkznvctx.html