【发布时间】:2017-12-01 05:18:25
【问题描述】:
对 React 非常陌生,我似乎被卡住了。这是一个简单的 Todo 应用程序,我基本上有 3 个组件,基本组件、输入组件和任务组件。我已经想出了如何编辑每个组件中的状态,但是在将状态从组件传递到组件时遇到了麻烦。
class App extends Component {
render() {
return (
<div id="appContainer">
<HeaderTitle />
<TaskInput />
<Task taskState={true} text="task one" />
<Task taskState={true} text="task two" />
<Task taskState={true} text="task three" />
</div>
);
}
}
class TaskInput extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
update(e) {
this.setState({inputValue: e.target.value});
console.log(this.state);
}
taskCreate(e) {
this.setState({text: this.state.inputValue, completeState: false});
console.log('button clicked');
console.log(this.state);
}
render () {
return (
<div className="taskInputContainer">
<TaskInputField update={this.update.bind(this)} taskCreate={this.taskCreate.bind(this)} />
</div>
)
}
}
class Task extends Component {
constructor(props) {
super();
this.state = {
completeState: false
}
}
toggleTask (e) {
this.setState({
completeState: !this.state.completeState
});
}
delete (item) {
}
render() {
return (
<div className="taskContainer" onClick={this.toggleTask.bind(this)}>
<div className={"taskState " + this.state.completeState}></div>
<div className={"taskText " + this.state.completeState }>{this.props.text}</div>
<div className="taskDelete"><i className="fa fa-times-circle-o" aria-hidden="true"></i></div>
</div>
);
}
}
const TaskInputField = (props) =>
<div className="taskInputContainer">
<input type="text" className="taskInputField" onChange={props.update}/>
<i className="fa fa-plus-circle" aria-hidden="true" onClick={props.taskCreate}></i>
</div>;
Task.propTypes = {
text: PropTypes.string.isRequired,
completeState: PropTypes.bool
};
Task.defaultProps = {
text: 'Task',
completeState: false
};
const HeaderTitle = () => (
<h1>Davids Todo List</h1>
);
export default App;
所以在 TaskInput 中有它自己的状态,我可以更新,但是我如何将它传递给父组件来更新和添加一个 Task 组件?另外,如何在不重新渲染整个内容的情况下添加任务组件?
【问题讨论】:
-
您不能将值从孩子传递给父母;取而代之的是,您可以在父级中编写一个带有特定参数的函数,将该函数传递给子级,然后在子组件中调用该函数,以提供来自子组件的值;像这样的东西:medium.com/@ruthmpardee/…