我有像这样渲染 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/