1 回答

TA贡献1757条经验 获得超7个赞
向组件添加状态,向组件添加 onChange 事件,在 onChange 函数中使用 setState 更新状态,使用状态值保护输入字段,以便它仅在评估为 true 时显示。当 onChange 被触发并调用 setState 时,渲染将自动重新触发(react 在状态更改时触发重新渲染)。下面是半伪代码:
class MyComponent extends React.Component {
state = {
showPrefixField: false;
}
updateShowPrefix(event) {
const newValue = event.currentTarget.value === 'yes' ? true : false; //ternary statement sets boolean to true when they click on yes
this.setState({showPrefixField: newValue}); // update state with true/false
}
render() {
<input type="radio" onChange={this.updateShowPrefix} value='yes' />
<input type="radio" onChange={this.updateShowPrefix} value='no' />
//the line below is a guard condition meaning anything following the ampersands will only execute if its true
{this.state.showPrefixField &&
<label>prefix:</label>
<input type="text" name="prefixFeild" />
}
}
添加回答
举报