简体   繁体   中英

Correct way to set checkbox default state using JSX

If HTML5 specifies that there is no value for the "checked" attribute that is reliably interpreted as the checkbox being unchecked*, is the behavior of the following JSX code potentially inconsistent between browsers? (It seems to work as expected for me in Chrome and IE.)

<input type="checkbox" checked={node.props.checked} />

If so, what is the standard way to accomplish this, considering that the following JSX is invalid?

<input type="checkbox" {node.props.checked? "checked" : ""} />

What values for checked and selected are false?

You will need to conditionally add the entire checked attribute, not just the value of the attribute. That way, if you don't add the attribute at all, you will reliably get an unchecked checkbox.

If you are using ReactJS, then according to this answer :

React is intelligent enough to omit the attribute if the value you pass to it is not truthy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM