gpt4 book ai didi

javascript - 一个列表项而不是所有列表项的 ReactJS 悬停/鼠标悬停效果

转载 作者:数据小太阳 更新时间:2023-10-29 06:14:16 24 4
gpt4 key购买 nike

我是 React 新手,所以这可能看起来很简单,也可能不是,我不确定。我正在建立一个基本的待办事项列表。我希望列表项上的鼠标悬停效果弹出“删除此”文本。但是到目前为止,对于我的代码,当我将鼠标悬停在一个列表项上时,“删除这个”会针对所有列表项弹出,而不仅仅是一个列表项。

当我尝试通过为单个列表项创建一个新组件来解决这个问题时,这似乎不起作用。非常感谢任何帮助!

class ToDosContainer extends React.Component {
constructor(props) {
super(props)

this.state = {
heading: 'Something You Need To Do?',
todos: [
'wake up',
'brush your teeth'
],
}

this.addToDo = this.addToDo.bind(this)
}

addToDo(todo) {
this.setState((state) => ({
todos: state.todos.concat([todo])
}))
}
render() {
return (
<div>
<h1>To Do List</h1>
<h3>{this.state.heading}</h3>
<AddToDo addNew={this.addToDo} />
<ShowList tasks={this.state.todos} />
</div>
)
}
}

class AddToDo extends React.Component {
constructor(props) {
super(props)

this.state = {
newToDo: ''
}

this.updateNewToDo = this.updateNewToDo.bind(this)
this.handleAddToDo = this.handleAddToDo.bind(this)

}

//I think I can delete this part
updateNewToDo(e) {
this.setState({
newToDo: e.target.value
})
}
//

handleAddToDo() {
this.props.addNew(this.state.newToDo)
this.setState({
newToDo: ''
})
}

render() {
return (
<div>
<input
type="text"
value={this.state.newToDo}
onChange={this.updateNewToDo}
/>
<button onClick={this.handleAddToDo}> Add To Do </button>
</div>
)
}
}

class ShowList extends React.Component {

constructor(props) {
super(props)

this.state = {
newToDo: ''
}
}

onMouseOver(e) {
this.setState({
text: 'delete me'
})
console.log('hey')
}

onMouseOut(e) {
this.setState({
text: ''
})
console.log('hey hey')

}

render() {
const { text } = this.state;
return (
<div>
<h4>To Do's</h4>
<ul>
{this.props.tasks.map((todo) => {
return <li onMouseEnter={this.onMouseOver.bind(this)} onMouseLeave={this.onMouseOut.bind(this)}> {todo} {text}</li>
})}
</ul>
</div>
)
}
}

ReactDOM.render(<ToDosContainer />, document.getElementById('helloworld'));

最佳答案

我会制作一个任务组件。您不想在 ListView 组件中设置文本的状态,因为 this.state.text 会被 map 中的每个任务共享。每个任务都应该知道自己的悬停,而不是其他子任务的悬停。

class Task extends React.Component {
state = {
text: ""
};
onMouseOver(e) {
this.setState({
text: "delete me"
});
}

onMouseOut(e) {
this.setState({
text: ""
});
}

render() {
return (
<li
onMouseEnter={this.onMouseOver.bind(this)}
onMouseLeave={this.onMouseOut.bind(this)}
>
{this.props.todo} {this.state.text}
</li>
);
}
}


class ShowList extends React.Component {
constructor(props) {
super(props);

this.state = {
newToDo: ""
};
}

render() {
const { text } = this.state;
return (
<div>
<h4>To Do's</h4>
<ul>
{this.props.tasks.map(todo => {
return <Task todo={todo} />;
})}
</ul>
</div>
);
}
}

关于javascript - 一个列表项而不是所有列表项的 ReactJS 悬停/鼠标悬停效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50633499/

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