gpt4 book ai didi

reactjs - 切换显示/隐藏特定元素

转载 作者:行者123 更新时间:2023-12-03 14:28:29 24 4
gpt4 key购买 nike

我有这个特定的代码,它显示了每个问题的问题列表和按钮。当我点击按钮时,它会显示问题的具体答案。我的问题是,我有很多问题,当我单击按钮时,它将显示所有答案,而不是该问题的具体答案。

这是代码

class App extends React.Component {
constructor(){
super()
this.state = {
answer: [],
isHidden: true
}
this.toggleHidden = this.toggleHidden.bind(this)
}

componentWillMount(){
fetch('http://www.reddit.com/r/DrunkOrAKid/hot.json?sort=hot')
.then(res => res.json())
.then( (data) => {
const answer = data.data.children.map(obj => obj.data);
this.setState({answer});
})
}

toggleHidden(){
this.setState({isHidden: !this.state.isHidden})
}

render(){
const answer = this.state.answer.slice(2)
return <div>
<h1>Drunk or Kid</h1>
{answer.map(answer =>
<div key={answer.id}>
<p className="title">{answer.title}</p>
<button onClick={this.toggleHidden}>Answer</button>
{!this.state.isHidden && <Show>{answer.selftext}</Show>}
</div>
)}
</div>
}
}
const Show = (props) => <p className="answer">{props.children}</p>

这里是 codepen 的链接

最佳答案

这是一个Codepen根据我的建议:

子组件的基础知识是:

class Question extends React.Component {
// Set initial state of isHidden to false
constructor() {
super();
this.state = {
isHidden: false
}
}
// Toggle the visibility
toggleHidden() {
this.setState({
isHidden: !this.state.isHidden
});
}
// Render the component
render() {
const { answer } = this.props;
return (
<div key={answer.id}>
<p className="title">{answer.title}</p>
<button onClick={ () => this.toggleHidden() }>Answer</button>
{this.state.isHidden && <Show>{answer.selftext}</Show>}
</div>
);
}
}

然后您将在父组件中将其映射为:

answer.map(answer =>
<Question answer={answer} key={answer.id} />
)

关于reactjs - 切换显示/隐藏特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41686002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com