2016-10-25 10 views
2

내가 목록 내부의 간단한 UL입니다라는 간단한 구성 요소가 반응한다. 각 l은 간단한 구성 요소입니다. 하나의 입력 필드를 렌더링하는 다른 부모 구성 요소와 리스트 구성 요소가 있습니다. 을 두드림 키 입력 입력란의 텍스트를 잡습니다. 예를 들어, handleNewText (inputText)이라는 함수를 호출하고 싶습니다. 그러나이 함수는 다른 구성 요소가 구성 요소에있는 다른 구성 요소를 채우는 데 사용하기 때문에 List 구성 요소 안에 있어야합니다.전화 하위 구성 요소 방법에

List 및 MyParent 구성 요소가 List에서 MyParent로 데이터 관리를 전달하는 것을 리팩토링하고 싶지 않습니다.

최초의 부모와 두 번째는 당신이 상위 구성 요소

목록을 렌더링에서 하위 구성 요소의 함수를 호출하는 심판의 사용을 만들 필요가 아이

class TodoComp extends React.Component { 
 
    constructor(props){ 
 
    super(props); 
 
    this.handleKeyPress = this.handleKeyPress.bind(this); 
 
    } 
 

 
    componentDidMpunt(){ 
 
    console.log(this._child.someMethod()); 
 
    } 
 

 

 
    handleKeyPress(event){ 
 
    if(event.key === 'Enter'){ 
 
     var t = event.target.value; 
 

 
    } 
 
    } 
 

 
    render(){ 
 
    return (
 
     <div> 
 
      <input 
 
      className="inputTodo" 
 
      type="text" 
 
      placeholder="want to be an hero...!" 
 
      onKeyPress={this.handleKeyPress} 
 
      /> 
 
      <List/> 
 
     </div> 
 
    ); 
 
    } 
 

 
} 
 

 

 
export default class List extends React.Component { 
 
    constructor() { 
 
    super(); 
 
    this.flipDone = this.flipDone.bind(this); 
 
    this.state = { 
 
     todos: Array(3).fill({ content: '', done: false}) 
 
    }; 
 
    } 
 

 
    flipDone(id) { 
 
    let index = Number(id); 
 

 
    this.setState({ 
 
     todos: [ 
 
     ...this.state.todos.slice(0, index), 
 
     Object.assign({}, this.state.todos[index], {done: !this.state.todos[index].done}), 
 
     ...this.state.todos.slice(index + 1) 
 
     ] 
 
    }); 
 
    } 
 

 
    render() { 
 

 
    const myList = this.state.todos.map((todo, index) => { 
 
     return (
 
     <Todo key={index} 
 
       clickHandler={this.flipDone} 
 
       id={index} 
 
       todo={todo} 
 
       handleText={this.handleText} 
 
     /> 
 
    ); 
 
    }) 
 

 
    return (
 
     <ul className="list"> 
 
     {myList} 
 
     </ul> 
 
    ); 
 
    } 
 

 

 
ReactDOM.render(<TodoComp />,document.getElementById('myList'));

+0

코드를 보여줄 수 있습니까? –

답변

4

입니다 상위의 구성 요소 :

<List ref="myList"/> 

한 다음과 같이 handleNewText() 기능에 액세스 this.refs.myList.handleNewText()

UPDATE :

심판이 더 이상 권장된다

문자열, 당신은 오히려 심판 콜백을 사용한다 반작용 this

<List ref={(ref) => this.myList=ref}/> 

다음 액세스 확인 하위 기능은 다음과 같습니다.

this.myList.handleNewText() 
관련 문제