怎么传递props

我在父组件发送了请求,返回了一些数据,但是现在子组件收不到数据,请问通过props怎么传递,具体的代码实现或是简单的案例

...... {

constructor(props) {
    // console.log(props); **这里输出没有得到数据thumbnails:{total: 0, url: Array(0)}**
    super(props);
    this.state = {
        thumbnail:[]
    };
};
render() {
return (
..........

componentWillReceiveProps(nextProps){
    //debugger
    console.log(nextProps);    //没有数据
    this.setState({
        thumbnail:nextProps.thumbnail
    })
阅读 2.3k
3 个回答

父组件获得了数据后 将你的数据存储在父组件的state当中 ,然后向子组件传递通过state去传递就好了
如:


//父组件 Parent
class Parent extends React.Component{
    constructor(props){
        super(props);
        this.state={
            parentDate:""
        }
    }
    handle(){
        //在这里请求拿到数据然后进行存储
        this.setState({
            parentDate:"XXXX"
        })
    }
    render(){
        return (
            <Child  parentDate={this.state.parentDate}/>
        )
    }
    //子组件
    class Child extends React.Component{
        constructor(props){
            super(props);
        }
        componentWillReceiveProps(nextProps){
            //在这里可以将接受到的props去存在子组件内
        }
        render(){
            return (
                <div>{"I get : "+this.props.parentData}</div>
            )
        }
    }
}

官方文档
使用时,父组件直接在子组件标签上写要传递的值,子组件可以在this.props获取到父组件传来的prop:

class Child extends Component {
  render() {
    return (
      <button className="child" onClick={this.props.onClick} >
        {this.props.value}
      </button>
    )
  }
}

父组件是直接写在子组件元素上的:

class Parent extends Component {
  render() {
    return (
<Child value='这是一个prop' 
   onClick={() => this.clickFunction(i)} //这是传递了一个函数作为prop />
    )
  }
}
componentWillReceiveProps (nextProps) {
    console.log(nextProps)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题