2017-01-09 79 views
3

我能夠傳遞數據,但我卡在這裏,如何將AddTodo component的狀態傳遞給Todos component?我的組件結構有什麼問題嗎?作爲道具傳遞狀態值到另一個組件es6

class AddTodo extends React.Component { 
    constructor(){ 
    super(); 
    this.state = {text: ''}; 
    } 
    onTextChanged(e){ 
    this.setState({text:e.target.value}); 
    } 
    addHandler(){ 
    alert(this.state.text); // pass this to Todos?? 
    } 
    render() { 
    return(
     <div> 
     <input type="text" onChange={(e)=>this.onTextChanged(e)} /> 
     <button onClick={()=>this.addHandler()}>Add</button> 
     </div> 
    ) 
    } 
} 

class Todos extends React.Component { 
    constructor(){ 
    super(); 
    this.data = ['write book','wash clothes','jogging']; 
    } 
    render() { 
    return (  
     <div> 
     <AddTodo/> 
     <ul> 
     {this.data.map((item)=><TodoItems key={item} item={item}/>)} 
     </ul> 
     </div> 
    ); 
    } 
} 

現場演示這裏http://jsbin.com/susadehacu/1/edit

回答

0

很簡單,你只需要在Todos添加一個方法將項目添加到列表中。這將作爲道具傳遞給您的AddTodo組件。

託多斯

constructor(){ 
    super(); 
    this.data = ['write book','wash clothes','jogging']; 
} 

addTodo(todo) { 
    // new array 
    let newData = this.data.slice(); 
    newData.push(todo); 
    this.setState({data: newData}); 
} 

... 

<AddTodo addTodo={(todo) => this.addTodo(todo)} /> 

AddTodo

addHandler(){ 
    this.props.addTodo(this.state.text); 
} 
相關問題