Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

javascript - 如何在ReactJS中预先选中一些复选框(How to precheck some checkbox in ReactJS)

My code has many atributes that have to be choosed by user, he can choose 0 or all and sometimes some atributes will come checked if this user has been choose the atributes before, i've try hard to do this with reactjs but checked and defaultChecked props are confuse to me, here my code sample.(我的代码中有许多必须由用户选择的属性,他可以选择0或全部,有时,如果此用户之前已经选择了该属性,则某些属性会被检查。我已经尽力使用reactjs做到这一点,但checked并使用defaultChecked道具让我感到困惑,这里是我的代码示例。)

class App extends React.Component { state = { colors: [ 'red', 'black', 'green', 'blue', 'white', 'yellow' ], checkedColors: [ 'blue', 'yellow' ] } handleSubmit(e) { e.preventDefault() const { target } = e const formData = new FormData(target) const checkedColors = formData.getAll('colors') this.setState({ checkedColors }) } render() { const { colors, checkedColors } = this.state return ( <form onSubmit={this.handleSubmit.bind(this)}> <ul> {colors.map((color, index) => ( <li key={index}> <input type='checkbox' name='colors' id={color} value={color} checked={checkedColors.some(chckColor => chckColor === color)} /> <label htmlFor={color}>{color}</label> </li> ))} </ul> <button>submit</button> <span>{checkedColors.join(', ')}</span> </form> ) } } ReactDOM.render(<App />, document.getElementById('root')) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>   ask by Jefter Rocha translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can achieve this by assigning a true boolean value to the checked attribute.(您可以通过为选中的属性分配一个布尔值来实现这一点。)

Sample code below:(下面的示例代码:) checked={ yourCondition ? true : false } If your condition is matched, the checkbox will be checked.(如果符合您的条件,则将选中该复选框。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...