有没有办法通过父组件控制子组件功能?

时间:2018-03-16 06:32:25

标签: javascript reactjs

我尝试构建图片上传工具,每个子组件都有自己的上传按钮。 有没有办法让父组件控制上传功能?

遵循以下代码:

子组件

class Child extends Component{
 constructor(props){
  super(props)
  this.state={
   imageUrl: 'base64'
  }
 }
 componentDidMount(){
  this.setState({imageUrl: this.props.image})
 }
 handleUpload(){
  axios.post(this.state.imageUrl);
 }
 render(){
  return(
   <div>
    <img src={this.state.imageUrl}/>
    <button onClick={this.handleUpload.bind(this)}></button>
   </div>
  ) 
 }
}

父组件

class Parent extends Component{
 constructor(props){
  super(props)
  this.state={
   imageFiles: [...image]
  }
 }
 componentDidMount(){

 }

 render(){
  return(
   <div>
    {
     this.state.imageFiles.map(image=>{
      return(
       <Child image={image}/>
      )
     })
    } 
   </div>
  ) 
 }
}

我知道如何通过父组件中<child handle={this.handle.bind(this)}/>的方式访问父组件函数到子组件。

是否有一些让父组件函数可以触发所有子组件的方法?

2 个答案:

答案 0 :(得分:1)

您可以在父组件中移动句柄功能,然后将其传递给子组件,如:

<Child image={image} onClickUpload={this.handleUpload}/>

答案 1 :(得分:0)

以下是相同的question

为子组件创建ref,然后在父级函数中调用它。