Javascript 使用es6 bind和react时将arg传递给函数
如果我在JSX中使用es6 arrow函数,那么我可以像这样传递来自另一个组件的道具Javascript 使用es6 bind和react时将arg传递给函数,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,如果我在JSX中使用es6 arrow函数,那么我可以像这样传递来自另一个组件的道具 class MyComponent extends Component({ myFunc(param){ console.log(param); } render( return( <button onClick="(param)=>myFunc(param)"></button> ) ) }) 类MyComponent扩展组
class MyComponent extends Component({
myFunc(param){
console.log(param);
}
render(
return(
<button onClick="(param)=>myFunc(param)"></button>
)
)
})
类MyComponent扩展组件({
myFunc(参数){
控制台日志(param);
}
渲染(
返回(
)
)
})
但是如果我用这种呢
class MyComponent extends Component({
constructor(){
this.myFunc = this.myFunc.bind(this);
}
myFunc(){
}
render(
return(
<button onClick={this.myFunc}></button>
)
)
})
类MyComponent扩展组件({
构造函数(){
this.myFunc=this.myFunc.bind(this);
}
myFunc(){
}
渲染(
返回(
)
)
})
如何传递参数?您在这行中犯了错误
constructor(){
this.myFunc = myFunc.bind(this);
}
这应该是有效的:
constructor(){
this.myFunc = this.myFunc.bind(this);
}
myFunc(props){
console.log(props);
}
你不能像第一个那样直接通过。但是您可以使用
e.target
以不同的方式访问。但我不确定你想要什么样的场景
class MyComponent extends Component({
constructor(){
this.myFunc = this.myFunc.bind(this);
}
myFunc(e){
console.log(e.target.arg);
}
render(){
return(
<button arg={yourargument} onClick={this.myFunc}></button>
)
}
})
类MyComponent扩展组件({
构造函数(){
this.myFunc=this.myFunc.bind(this);
}
myFunc(e){
console.log(e.target.arg);
}
render(){
返回(
)
}
})
您想将其用于什么目的?它是用来删除子对象的吗?@illusionist我可能想把一些东西传给子组件。onClick={this.myFunc.bind(this)}
或onClick={e=>this.myFunc(e)}
你可以这样使用它:myFunc(param1,param2,param3){console.log(param1,param2,param3)}
不要在构造函数中绑定它。