-1

I tried to build a image upload tool, every child component have there own upload button. Is there the way to let the upload function control by parent component?

following the code:

Child Component

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>
  ) 
 }
}

Parent Component

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>
  ) 
 }
}

I know how to access the parent component function to child component by this way <child handle={this.handle.bind(this)}/> in the parent component.

Is there some method to let parent component functions can trigger all the child component?

Champer Wu
  • 1,101
  • 3
  • 13
  • 32
  • 2
    Possible duplicate of [Call child method from parent](https://stackoverflow.com/questions/37949981/call-child-method-from-parent) – Mike Kor Mar 16 '18 at 06:43

2 Answers2

1

You could move handle function in the parent component, then pass it to the child component like:

<Child image={image} onClickUpload={this.handleUpload}/>
PhatHoang
  • 23
  • 6
0

Here is the same question

Make a ref for a child component and then call it within parent's function.

Mike Kor
  • 876
  • 5
  • 14