技术研发

react子组件、父组件相互传值

2018-12-12  本文已影响0人  gzxwnt

子组件传图片路径imgUrl值给父组件,父组件传imgaddr值给子组件
子组件:

export default class Son extends React.Component {
//获取父组件传过来的imgaddr值
    constructor(props) {
        super(props);
        this.state = {
            imgaddr:props.imgaddr,
        };}

//通过回调函数传值给父组件
    onSuccess=(res, dataUrl)=> {
        this.refs.targetViewer.src = dataUrl;
        this.props.getImg(res.data.imgurl);
    };
  
//通过this.props.imgaddr绑定父组件传过来的值
    render() {
        return (
                <div>
                    <img
                        src={this.props.imgaddr}
                    />
                </div>
    }
}

父组件:

export default class Father extends Component {

 constructor(props) {
    super(props);
    this.state = {
        imgurl:'',
    };}

//通过getImg方法取到子组件传过来的imgurl值
  getImg = (imgurl) => {
      this.setState({
          imgurl:imgurl
      });
  };

//父组件通过record传imgaddr值给子组件
render: (value, index, record) => {
          return (
              <EditDialog
                record={record}
              />
          );
        },

//在组件CropUploadImage中绑定imgurl值
<CropUploadImage
           getImg={this.getImg}
  />
  }
上一篇下一篇

猜你喜欢

热点阅读