gpt4 book ai didi

javascript - 更改组件 react js 的 onClick 函数?

转载 作者:行者123 更新时间:2023-11-29 16:45:21 24 4
gpt4 key购买 nike

我有带按钮的组件和 2 个功能。按钮组件用于各种组件。对于某些人来说,onclick 事件需要一个函数,而其他函数则需要第二个。如何更改 onclick 事件的功能?我正在使用 this answer ,但在我的组件中总是未定义。

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>

);
}

在另一个组件中:

<FormGroup>
<Col mdOffset={5} md={7}>
<MyButtonComponent onClick={this.secondFunction} data-url="someurl.com"></MyButtonComponent>
</Col>
</FormGroup>

也试过添加

onClick={e => this.secondFunction(e)} 

按钮componentm但总是报错

_this2.secondFunction is not a function

最佳答案

问题似乎与您使用 this 的方式有关- 当您调用 this.secondFunction<FormGroup>其他组件的元素,它正在寻找 secondFunction那个组件中。您已经定义了 secondFunctionMyButtonComponent , 所以它返回为 undefined .

您可以通过在 MyButtonComponent 中定义一个单击处理程序来解决这个问题它根据您可以在外部更新的 Prop 选择要调用的函数。例如

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>

关于javascript - 更改组件 react js 的 onClick 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42091042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com