Javascript 是否有办法通过父组件控制子组件功能?
我试图建立一个图像上传工具,每个子组件都有自己的上传按钮。 有没有办法让上传功能通过父组件进行控制 遵守守则: 子组件Javascript 是否有办法通过父组件控制子组件功能?,javascript,reactjs,Javascript,Reactjs,我试图建立一个图像上传工具,每个子组件都有自己的上传按钮。 有没有办法让上传功能通过父组件进行控制 遵守守则: 子组件 class Child extends Component{ constructor(props){ super(props) this.state={ imageUrl: 'base64' } } componentDidMount(){ this.setState({imageUrl: this.props.image}) } handleU
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>
)
}
}
类子级扩展组件{
建造师(道具){
超级(道具)
这个州={
imageUrl:'base64'
}
}
componentDidMount(){
this.setState({imageUrl:this.props.image})
}
handleUpload(){
post(this.state.imageUrl);
}
render(){
返回(
)
}
}
父组件
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>
)
}
}
类父级扩展组件{
建造师(道具){
超级(道具)
这个州={
图像文件:[…图像]
}
}
componentDidMount(){
}
render(){
返回(
{
this.state.imageFiles.map(image=>{
返回(
)
})
}
)
}
}
我知道如何通过父组件中的
将父组件函数访问到子组件
有什么方法可以让父组件函数触发所有子组件吗?这里也是一样
为子组件创建一个
ref
,然后在父组件的函数中调用它。您可以在父组件中移动句柄函数,然后将其传递给子组件,如:
<Child image={image} onClickUpload={this.handleUpload}/>
如果子组件是迭代器,并且ref
将实现最后一个组件函数,则可以实现所有子组件?只需确保将ref添加到所有组件hanks,我发现use for loop可以做到这一点