React JS - 如何在选择单选选项时显示文本表单?

React JS - How can you unveil a text form upon selecting a radio option?

上下文:

问题:

从图中可以看出,用户有两个选择,我只希望在用户选择 "Yes, set prefix" 时显示 "Prefix" 输入框。为了提供更多上下文,用户的输入稍后将用于生成实时预览,如图像右侧所示。 Ant Design 似乎没有与这种特定情况相关的示例,我正在尝试使用 React JS 变得更好,因此非常感谢任何见解。即使你能给我指出很棒的资源。

谢谢!

向您的组件添加状态,向您的组件添加 onChange 事件,使用 onChange 函数内的 setState 更新状态,使用状态值保护输入字段,以便它仅在评估为真时显示。当触发 onChange 并调用 setState 时,渲染将自动重新触发(反应触发器在状态更改时重新渲染)。下面是半伪代码:

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" />
  }

}