Передача функции с параметрами через опоры на реакциях
У меня есть функция, которая поступает от родителя, вплоть до дочернего элемента дочернего элемента в иерархии компонентов. Обычно это не слишком большая проблема, но мне нужно получить параметр от дочернего элемента.
В настоящее время я получаю это сообщение об ошибке: Недоступно (в обещании) TypeError: this.props.myFunction не является функцией.
Вот пример кода для того, что я делаю:
class SomeComponent extends Component{
constructor(props){
super(props);
//does whatever stuff
this.myFunction = this.myFunction.bind(this);
}
//(only applicable to raw and normal forms)
myFunction(param){
console.log('do something: ', param);
}
render(){
return (<div><ChildComponent1 myFunction={()=>this.myFunction()}/></div>)
}
}
class ChildComponent1{
render(){
return (<div><ChildComponent2 myFunction={()=>this.props.myFunction()}/></div>)
}
}
class ChildComponent2{
render(){
return (<Button onClick={()=>this.props.myFunction(param)}>SomeButton</Button>)
}
}
Итак, просто для этого: я передаю myFunction как опору из SomeComponent вплоть до ChildComponent2, в котором я хочу, чтобы он вызывался всякий раз, когда нажимали кнопку и передавали параметры из ChildComponent2.
Спасибо!
Ответы
Ответ 1
Я не понимаю, почему вы получите эту ошибку, но вы должны делать myFunction={this.myFunction}
и myFunction={this.props.myFunction}
:
class SomeComponent extends Component{
constructor(props){
super(props);
//does whatever stuff
this.myFunction = this.myFunction.bind(this);
}
//(only applicable to raw and normal forms)
myFunction(param){
console.log('do something: ', param);
}
render(){
return (<div><ChildComponent1 myFunction={this.myFunction}/></div>)
}
}
class ChildComponent1{
render(){
return (<div><ChildComponent2 myFunction={this.props.myFunction}/></div>)
}
}
class ChildComponent2{
render(){
return (<Button onClick={()=>this.props.myFunction(param)}>SomeButton</Button>)
}
}
Обертка вызова функции внутри другой (стрелка) функции просто не нужна и не будет перенаправлять параметр должным образом (так как все ваши промежуточные функции стрелки не принимают параметр).
Ответ 2
Альтернативный и IMO более чистый способ сделать это будет так:
class SomeComponent extends Component{
myFunction = param => {
console.log('do something: ', param);
}
render(){
return (
<div>
<ChildComponent1 onClick={this.myFunction}/>
</div>)
}
}
class ChildComponent1{
render(){
return (<div><ChildComponent2 onClick={this.props.onClick}/></div>)
}
}
class ChildComponent2{
render(){
const { onClick } = this.props // destructure
return (<Button onClick={()=>onClick(param)}>SomeButton</Button>)
}
}