我想了解props
和state
是如何進出。我正在評論我理解的代碼片段,但也有一些我不能這樣做,因爲我沒有得到正在發生的事情。這個React組件的每個部分是做什麼的,狀態和道具是如何進行的?
或者在這裏你可能會看到代碼,以及:你如何解釋什麼是onChange
功能上做TodoItems
組件
class TodoList extends React.Component {
// THIS IS THE PARENT COMPONENT
// WE DECLARE THE TYPE OF PROPS
static propTypes = {
todos: React.PropTypes.array
}
// INITIAL STATE OF THE COMPONENT
constructor(props) {
super(props)
this.state = { todos: this.props.todos || [] }
}
addTodo = (item) => {
// WE START MODIFYING THE STATE OF THE COMPONENT
this.setState({todos: this.state.todos.concat([item])});
}
render() {
return (
<div className="panel panel-default TodoList">
<h3>TODO List</h3>
<TodoItems items={this.state.todos}/>
<TodoInput addTodo={this.addTodo}/>
</div>
);
}
};
class TodoItems extends React.Component {
static propTypes = {
items: React.PropTypes.array.isRequired
}
constructor(props) {
super(props);
}
render() {
let createItem;
createItem = (item, index) => {
return (
<li key={index} className="list-group-item">{item}</li>
);
};
return (
<ul className="TodoItems list-group">
{this.props.items.map(createItem)}
</ul>
);
}
};
class TodoInput extends React.Component {
constructor (props) {
super(props);
this.state = {item: ''};
}
onChange = (e) => {
this.setState({item: e.target.value});
}
handleSubmit = (e) => {
e.preventDefault();
this.props.addTodo(this.state.item);
this.setState({item: ''});
}
render() {
return (
<form onSubmit={this.handleSubmit} className="TodoInput">
<div className="input-group">
<input type="text"
className="form-control"
placeholder="Search for..."
onChange={this.onChange} value={this.state.item}/>
<span className="input-group-btn">
<input className="btn btn-default"
type="submit" value="Add" />
</span>
</div>
</form>
);
}
};
React.render(<TodoList todos={['red','blue']}/>, document.getElementById('container'));
。
或者你怎麼解釋的代碼段是這樣的:
<TodoItems items={this.state.todos}/>
<TodoInput addTodo={this.addTodo}/>
爲什麼this.state.todos
設置props
那裏,和爲什麼叫addTodo={}
那裏this.addTodo
?
有意義從頭開始https://facebook.github.io/react/ – zerkms
這可能是一個更有用的資源。幫助了我很多https://facebook.github.io/react/docs/thinking-in-react.html –