Sai*_*han 11 javascript checkbox reactjs
我搞乱了复选框,我想知道有没有办法可以通过调用函数取消选中按钮上的复选框?如果是这样?我怎样才能做到这一点?
<input type="checkbox" className="checkbox"/>
<button onClick={()=>this.unCheck()}
Run Code Online (Sandbox Code Playgroud)
如何以编程方式取消选中该复选框,如果我有多个使用map函数动态生成的复选框,该怎么办?如果我愿意,我怎样才能取消选中它们?
May*_*kla 11
checked您可以使用复选框的属性来切换复选框的状态.
可能的方法:
1-您可以使用ref复选框和onClick按钮,使用ref您可以取消选中该复选框.
2-您可以使用受控元素,意味着将state变量框的状态存储在变量中,并在单击按钮时更新.
通过使用ref检查此示例,ref为每个复选框分配唯一,然后在onClick函数内传递该项的索引,使用该索引切换特定的checkBox:
class App extends React.Component{
constructor(){
super();
this.state = {value: ''}
}
unCheck(i){
let ref = 'ref_' + i;
this.refs[ref].checked = !this.refs[ref].checked;
}
render(){
return (
<div>
{[1,2,3,4,5].map((item,i) => {
return (
<div>
<input type="checkbox" checked={true} ref={'ref_' + i}/>
<button onClick={()=>this.unCheck(i)}>Toggle</button>
</div>
)
})}
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'))Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>Run Code Online (Sandbox Code Playgroud)
检查这个受控元素的例子,意味着state在state变量里面存储复选框,然后点击按钮改变那个值:
class App extends React.Component{
constructor(){
super();
this.state = {value: []}
}
onChange(e, i){
let value = this.state.value.slice();
value[i] = e.target.checked;
this.setState({value})
}
unCheck(i){
let value = this.state.value.slice();
value[i] = !value[i];
this.setState({value})
}
render(){
return (
<div>
{[1,2,3,4,5].map((item,i) => {
return (
<div>
<input checked={this.state.value[i]} type="checkbox" onChange={(e) => this.onChange(e, i)}/>
<button onClick={()=>this.unCheck(i)}>Toggle</button>
</div>
)
})}
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'))Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>Run Code Online (Sandbox Code Playgroud)
使用纯 JavaScript,您可以实现如下所示的效果。
function unCheck() {
var x = document.getElementsByClassName("checkbox");
for(i=0; i<x.length; i++) {
x[i].checked = false;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
反应
已检查
<input type="radio" name="count" value="minus" onChange={this.handleRadioChange} checked={this.state.operation == "minus"} /> DecrementRun Code Online (Sandbox Code Playgroud)
2.使用参考
<input type="radio" name="count" ref="minus" /> Decrement
onSubmit(e){ this.refs.minus.checked = false }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17408 次 |
| 最近记录: |