【问题标题】:Checkbox checked in React.js在 React.js 中选中的复选框
【发布时间】:2018-01-31 19:59:28
【问题描述】:

我正在尝试像这样在 React.js 中使用 .checked() javascript 函数:

componentDidMount () {
    document.getElementById("myCheck").checked = true;
}

但我的控制台出现错误:“la propriété 'checked' n'existe pas sur le type HTMLlement”

如何在 React.js 中使用它?

谢谢

【问题讨论】:

  • 在 React 中,您必须更新状态才能重新渲染组件。请发布更多代码。
  • 为什么要这样? react 提供了一种更好的控制元素的方法,只需将<input checked={true} onChange={....}/> 用于controlled component,如果要使用uncontrolled component 则使用<input defaultChecked={true}/>
  • 我会依赖您的组件状态来获取复选框状态,而不是手动修改 DOM 的任何属性。看看this question and answer,因为它处理了一个非常相似的问题。
  • @MayankShukla 谢谢你的回答,很简单..我没想到!谢谢

标签: reactjs


【解决方案1】:

它对我有用

<div className='container'>
    <input type='checkbox' ref='myAwesomeCheckbox' id={'scales'} />
    <label fhtmlForor="scales">Scales</label>
</div>

componentDidMount = () => {
  this.refs.myAwesomeCheckbox.checked = true;
}

【讨论】:

    猜你喜欢
    • 2016-06-29
    • 2021-10-22
    • 2017-01-09
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 2022-01-21
    • 2014-09-27
    相关资源
    最近更新 更多