Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React Props 和 State #110

Open
yangtao2o opened this issue Apr 14, 2020 · 0 comments
Open

React Props 和 State #110

yangtao2o opened this issue Apr 14, 2020 · 0 comments

Comments

@yangtao2o
Copy link
Owner

yangtao2o commented Apr 14, 2020

React 中的 props 是什么

React 中的组件 (包括 Class Component 和 Functional Component) 对应于 JavaScript 的函数,而 props 就相当于这个构造函数的入参。其目的是为了实现数据从父组件到子组件的流动和组件的复用。
在 Class Component 中这样使用 props:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

在 Functional Component 中这样使用:

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

React 中所有的组件都应该是 “纯函数”,也就是说,入参 props 是不可以在组件内部被直接更改的。

props 不仅仅可以传递数据,还可以传递回调函数:

function Welcome(props) {
  return <button onClick={props.callback}>Hello, {props.name}</button>;
}

props 与解构赋值,其主要应用于给组件的子组件直传 props:

function Button2({ keyword, ...propsForButton }) {
  return (
    <div>
      keyword:{props.keyword}
      <button {...propsForButton} class="sub-button" />
    </div>
  );
}

学习资料

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant