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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…