【发布时间】:2019-08-02 09:09:57
【问题描述】:
我想使用引导开关来 React。我正在初始化组件并传递道具。但是当我通过单击更改按钮的状态时,更改功能不会触发。该按钮似乎工作正常,但有些东西覆盖了输入字段的 onChange 函数。
如何确定我的 onChange 函数的优先级?还是有更好的解决方案?
import React, { Component } from 'react'
class ReactBootstrapSwitch extends Component {
constructor(props) {
super(props)
this.state = {
isChecked: false
}
this.onChangeHandler = this.onChangeHandler.bind(this)
}
componentWillMount() {
this.setState({
checkBoxText: this.props.checkBoxText,
isChecked: this.props.isChecked
})
}
componentDidMount() {
window.$(`[name=${this.props.id}]`).bootstrapSwitch();
}
onChangeHandler(event) {
alert('Hi')
this.setState(function (previousState, props) {
if (previousState.checked === true) {
alert('A')
} else {
alert('B')
}
return {
isChecked: !this.state.isChecked
}
}
)
}
render() {
return (
<div className="form-check form-check-switch form-check-switch-left" >
<label className="form-check-label" >
<input onChange={event => this.onChangeHandler(event)}
name={this.props.id}
type="checkbox"
className="form-check-input form-check-input-switch"
data-off-color="warning"
data-on-text="On"
data-off-text="Off"
checked={this.state.isChecked}>
</input>
<b>{this.state.checkBoxText}</b>
</label>
</div>
)
}
}
export default ReactBootstrapSwitch
【问题讨论】:
-
您收到警报了吗?
-
不,这就是问题所在。它没有运行我的 onChangeHandler 函数
-
bootstrapSwitch是否有效?你换了吗? -
你是说文档吧?
-
你为什么不试试这个 - npmjs.com/package/react-bootstrap-switch 。使用它你不必担心 jquery 和初始化。
标签: javascript reactjs