组件通过props来接收传递给组件的内容

传递数据

在组件标签上添加属性即可向组件传递数据

  1. // 向组件abc 传递一个name属性值为abc
  2. ReactDOM.render(<Abc name='abc'/>)

接收数据

函数组件

函数组件接收数据props直接作为形参

  1. const Abc = props = >{
  2. return (
  3. <div>{props.name}</div>
  4. )
  5. }

类组件

类组件通过this.props接收

  1. class Abc extends React.Componet{
  2. render(){
  3. return (
  4. <div>{this.props.name}</div>
  5. )
  6. }
  7. }

注意

  1. // props 是一个对象 传递数据时可以是任意类型的数据 而且没有数量限制
  2. <Abc name="abc"
  3. whide={120}
  4. arr={[1,2,3]}
  5. fn={()=>{console.log('fn')}}
  6. tag={<div>JSX</div>
  7. }/>
  8. // props接收到的数据只读不能修改
  9. // constructor方法中无法直接获取到props需要将其作为参数 并在super()方法中调用
  10. class Abc extends React.Componet{
  11. constrnctor(props){
  12. super(props)
  13. console.log(props)
  14. }
  15. rendet(){
  16. return (
  17. <div>注意</div>
  18. )
  19. }
  20. }