javascript - React - 单击按钮时如何显示相关元素

标签 javascript reactjs

我有像这样渲染 jsx 的组件

<section>

    <div>
        <input type="text" class="hide" />
        <button id={item.uniqueID}>show input</button>
    </div>

    <div>
        <input type="text" class="hide" />
        <button id={item.uniqueID}>show input</button>
    </div>

    <div>
        <input type="text" class="hide" />
        <button id={item.uniqueID}>show input</button>
    </div>
</section>

我想要这种行为,当我单击第一个 div 中的按钮时,第一个 div 中的输入将显示。同样,我单击第三个 div 中的按钮,第三个 div 中的输入将显示。

你如何在 react 中做到这一点?

最佳答案

如果是我,我会用以下 Material 制作一个新组件: 显示输入

我们称之为<InputToggler/>

然后它自己的输入将具有 inputHidden 状态,并使用类来确定它是否应该显示,并且按钮将有一个 onclick 处理程序来切换隐藏或显示状态。这是一支笔,准确地显示了这一点

http://codepen.io/finalfreq/pen/VKPXoN

class InputToggler extends React.Component {
  constructor() {
    super();

    this.state = {
      inputHidden: true
    }
  }

  toggleInput = () => {
    this.setState({
      inputHidden: !this.state.inputHidden
    })
  };

  render() {
    const inputClass = this.state.inputHidden ? 'hide' : '';
    const buttonLabel = this.state.inputHidden ? 'show input' : 'hide input'
    return (
      <span>
        <input type="text" className={inputClass} />
        <button onClick={this.toggleInput} id={this.props.item.uniqueID}>          
          {buttonLabel}
        </button>
      </span>
     )
  }
}

关于javascript - React - 单击按钮时如何显示相关元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40407955/

相关文章:

javascript - 在js中进行异步服务调用的最轻量级方法是什么?

javascript - jQuery 动画左右移动

javascript - 在 Javascript 中使用 JSON 数组填充 HTML

javascript - ReactJS 不呈现我的 API 调用结果

css - 如何在 react 样式组件中添加 'title' 标签(用于工具提示)

reactjs - React Admin - 如何隐藏操作按钮

javascript - Blazor:Google map JS API

javascript - 在 JavaScript 中比较三个数组

javascript - Reactjs 不断抛出错误 "TypeError: this.goActive is not a function"

javascript - 如何在node.js和react中的某些数字后显示分页点