gpt4 book ai didi

javascript - 在 React 中将组件 props 传递给父组件时无法绑定(bind)事件

转载 作者:行者123 更新时间:2023-12-02 21:25:23 25 4
gpt4 key购买 nike

我有这段代码(粘贴在下面),我试图将“id”绑定(bind)到 onChange 事件以将其传递给父组件。

问题:onChange={this.props.markComplete.bind(this, id)} 返回错误:TypeError: 无法读取未定义的属性“bind”

如果我将 this.props.markComplete.bind(this, id) 替换为 this.markComplete.bind(this, id),则不会出现错误。我在做错的地方有点迷失。

注意:除了“绑定(bind)”之外,传递的属性按预期工作。

代码:


export class Tasks extends Component {
getStyle = () => {
return {
textDecoration: this.props.todo.completed ? "line-through" : "none"
};
};

render() {
const { id, title } = this.props.todo;
return (
<div style={this.getStyle()}>
<input
type="checkbox"
name="task"
checked={this.props.todo.completed ? true : null}
onChange={this.props.markComplete.bind(this, id)}
/>
<label>{title}</label>
</div>
);
}
}

export default Tasks;

最佳答案

您可以简单地调用通过 props 传递的 markComplete 而无需 .bind-ing:

const { Component } = React,
{ render } = ReactDOM,
rootNode = document.getElementById('root')

const taskList = [
{id:0, title: 'Do something', completed: false},
{id:1, title: 'Do something else', completed: false},
{id:2, title: 'Do some other stuff', completed: true},
]

class Task extends Component {
render() {
const { id, title, completed } = this.props;
return (
<div style={{backgroundColor:this.props.completed ? 'green' : 'none'}}>
<input
type="checkbox"
name="task"
checked={completed}
onChange={() => this.props.markComplete(id)}
/>
<label>{title}</label>
</div>
);
}
}

class TaskBoard extends Component {
constructor(props){
super(props)
this.state = {tasks:this.props.tasks}
this.handleComplete = this.handleComplete.bind(this)
}

handleComplete(taskId, completed){
const tasks = [...this.state.tasks],
completedTask = tasks.find(({id}) => id == taskId)
completedTask.completed = true
this.setState({tasks})
}

render(){
return(
this.state.tasks.map(task => <Task {...{key:task.id, markComplete:this.handleComplete,...task}} />)
)
}
}

render(<TaskBoard tasks={taskList} />, rootNode)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>

关于javascript - 在 React 中将组件 props 传递给父组件时无法绑定(bind)事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60753680/

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