Javascript 是否更改组件的onClick函数?
我有按钮组件和2个功能。按钮组件用于各种组件。对于某些情况,需要一个onclick事件函数,另一个为-second。如何更改onclick事件的函数?我正在使用,但在我的组件中总是没有定义Javascript 是否更改组件的onClick函数?,javascript,reactjs,Javascript,Reactjs,我有按钮组件和2个功能。按钮组件用于各种组件。对于某些情况,需要一个onclick事件函数,另一个为-second。如何更改onclick事件的函数?我正在使用,但在我的组件中总是没有定义 export default class MyButtonComponent extends Component { constructor(props) { super(props); propTypes: { onClick: PropTypes.func };
export default class MyButtonComponent extends Component {
constructor(props) {
super(props);
propTypes: {
onClick: PropTypes.func
};
this.state = { loading: false, api_url: "http://localhost:8000" };
}
static get DefaultProps() {
return {
onClick: this.firstFunction(event)
}
}
firstFunction(){
/*some code*/
}
secondFunction(){
/*some code*/
}
render() {
return (
<LaddaButton
loading={this.state.loading}
onClick={this.props.onClick}
className='submit'
data-color="#eee"
data-style={SLIDE_UP}
data-spinner-size={30}
data-spinner-color="#ddd"
data-spinner-lines={12}
data-url={this.props.url}
>
Отправить
</LaddaButton>
);
}
到按钮组件M,但总是出现错误
_this2.secondFunction is not a function
由于您将
secondFunction()
作为一个道具传递给MyButtonComponent
组件,因此它不能在MyButtonComponent
组件中定义,而是在包含以下代码的组件中定义
<FormGroup>
<Col mdOffset={5} md={7}>
<MyButtonComponent onClick={this.secondFunction} data-url="someurl.com"></MyButtonComponent>
</Col>
</FormGroup>
检查答案以更好地理解流程问题似乎在于如何使用
this
-当您调用其他组件的
元素中的this.secondFunction
时,它正在该组件中查找secondFunction
。您已经在MyButtonComponent
中定义了secondFunction
,因此它返回为undefined
您可以通过在MyButtonComponent
中定义一个单击处理程序来解决这个问题,该处理程序根据您可以在外部更新的道具选择要调用的函数。例如
function myClickHandler(e) {
if(useFirst) {
this.firstFunction(e);
} else {
this.secondFunction(e);
}
}
然后可以在其他组件的渲染方法中更改该属性,例如
<FormGroup>
<Col mdOffset={5} md={7}>
<MyButtonComponent useFirst=false data-url="someurl.com"></MyButtonComponent>
</Col>
</FormGroup>
是否在定义了
的父组件中定义了secondFunction
?否,来自另一个组件的表单组,按钮组件中定义了secondFunction。secondFunction
不应在MyButtonComponent中定义,它应该在父组件中定义。你想传递给button某种标志,指定应该从button激发什么效果方法,还是想传递从父组件激发的方法?第二个变量似乎是我需要的。这是一个比传递函数更优雅的解决方案,因为组件的属性非常复杂灵活。
<FormGroup>
<Col mdOffset={5} md={7}>
<MyButtonComponent onClick={this.secondFunction.bind(this)} data-url="someurl.com"></MyButtonComponent>
</Col>
</FormGroup>
function myClickHandler(e) {
if(useFirst) {
this.firstFunction(e);
} else {
this.secondFunction(e);
}
}
<FormGroup>
<Col mdOffset={5} md={7}>
<MyButtonComponent useFirst=false data-url="someurl.com"></MyButtonComponent>
</Col>
</FormGroup>