禁用React Js中的元素

时间:2018-05-20 06:32:06

标签: javascript reactjs

我是新的反应Js,我想根据条件设置禁用一些元素

我的表单中有三个元素,一个选择和两个输入

根据所选项目,必须禁用其中一项输入

这是我的组件代码:

class AddUser extends React.Component {

constructor(props) {
super(props);

this.state = {
user: {
}

};

}

render() {
    if (this.props.user) {
        this.state.user= this.props.user;
    }    

return (

        <div className="form-group">
            <label className="control-label">type<span className="symbol required"></span></label>
            <select className="form-control" name="CompanyMeetingType" value={this.state.user.type>
                <option value="1"> type1</option>
                <option value="2">type2</option>
                <option value="3">both</option>
            </select>
        </div>

        <div className="form-group">
            <label className="control-label">type1(%)<span className="symbol required"></span></label>
            <input required type="text" name="type1" className="form-control" disabled={this.state.user.type ==2} />
        </div>

        <div className="form-group">
            <label className="control-label">type1(%)<span className="symbol required"></span></label>
            <input required type="text" name="type2" className="form-control" disabled={this.state.user.type ==1} />
        </div>
)

}

当我更改所选项目时,禁用正常工作,但当我在编辑模式下提交选择元素时禁用不起作用

2 个答案:

答案 0 :(得分:1)

class Application extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        value: '1'
    }
    this.handleSelect = this.handleSelect.bind(this);
}
handleSelect(e) {
    console.log('enter');
    this.setState({
        value: e.target.value
    })
}
render() {
    console.log(this.state.value)
    return ( 
      <div >
        <select value = { this.state.value} onChange = {this.handleSelect} >
         <option value = "" >select value </option>
         <option value = "1" >value 1 </option>
         <option value = "2" >value 2 </option>
         <option value = "3" >both </option>
         </select> 
         <br / >
        <hr / >
        <input type = "text" disabled = {this.state.value == 1 || this.state.value == 3 }/>
        < br / > < br / >
        < input type = "text" disabled = { this.state.value == 2 || this.state.value == 3 }/> 
      < /div>
     );
    }
  }
React.render( < Application / > , document.getElementById('app'))

你唯一缺少的是handleSelect函数,它处理select值的事件并设置状态。它可以完美地运行。如果你想预先默认禁用任何输入标记,那么只需在状态中传递该值,这样当组件将呈现该标记将被禁用时。

答案 1 :(得分:0)

我没有看到onChange处理程序。尝试:

<select 
  className="form-control" 
  name="CompanyMeetingType" 
  value={this.state.user.type} 
  onChange={(e) => this.setState({ user: { type: e.target.value } })}>
   <option value="1"> type1</option>
   <option value="2">type2</option>
   <option value="3">both</option>
</select>