【问题标题】:React JS - How can you unveil a text form upon selecting a radio option?React JS - 如何在选择单选选项时显示文本表单?
【发布时间】:2020-08-14 03:10:29
【问题描述】:

上下文:

问题:

从图片中可以看出,用户有两个选项,如果用户选择“是,设置前缀”,我只希望显示“前缀”输入框。为了提供进一步的上下文,用户的输入稍后将用于生成实时预览,如图像右侧所示。 Ant Design 似乎没有与这种特定情况相关的示例,我正在尝试更好地使用 React JS,因此任何见解都将不胜感激。即使您可以向我指出很棒的资源。

谢谢!

【问题讨论】:

    标签: javascript reactjs forms radio-button


    【解决方案1】:

    向组件添加状态,向组件添加 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" />
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 1970-01-01
      • 2020-09-19
      • 2016-08-17
      • 2020-05-14
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      • 1970-01-01
      相关资源
      最近更新 更多