后端学前端之 React

React 组件之间传递参数 Props

2020-01-12  本文已影响0人  卡西法大人

React 的组件可以放入其他组件中去,有的时候,需要根据不同的调用显示不同的效果。这个时候,就需要向这个组件中传入参数。React 中提供了 props 可以传递参数。props 是传递进来的参数,是不可变得,在使用中,只能通过 props 的值去判断要显示什么样的结果,不能通过和用户交互。如果需要通过和用户的交互进行判断或者使用参数,则应该使用 state。
在 React 源码中,props 是这样定义的:

readonly props: Readonly<P> & Readonly<{ children?: ReactNode }>;

所以在组件中使用 props 变量也是 Component 父类中的变量。使用的时候是,this.props 的参数内容。比如想要定义一个参数名为text。使用的时候就是:this.props.text,下面的组件就使用 text 参数显示传入参数的内容:

class Hello extends Component {
    constructor(props) {
        super(props)
    }
    render() {
        return (
            <h1>{this.props.text}</h1>
        )
    }
}

这样,在使用这个组件的时候,只要在标签中,给参数赋值就好了:

class App extends Component {
  render() {
    return (
      <div>
        <h1>this is App</h1>
        <Hello text= "this is use props" />
      </div>
    )
  }
}

export default App;

这样就可以在页面上看到下面的部分,是 h1 标签中传入的变量值。效果如下:

上一篇 下一篇

猜你喜欢

热点阅读