2017-04-06 4 views
0

사용자에게 UI에 표시된 단어를 입력하도록 요청하는 슈퍼 간단한 응용 프로그램에 반응합니다. 사용자가 올바르게 입력하면 앱에 다른 단어가 표시되는 등의 효과가 있습니다.부모 구성 요소에서 입력을 지우는 ReactJS

한 가지를 제외하고는 거의 효과가 있습니다. 단어를 올바르게 입력 한 후에 입력 요소를 지워야합니다. 그것이 말하는 곳

// the app 
class AppComponent extends React.Component { 
    constructor() { 
     super(); 
     this.state = { 
     words: ['alpha', 'bravo', 'charlie'], 
     index: 0 
     }; 
    } 
    renderWordsource() { 
     const word = this.state.words[this.state.index]; 
     return <WordsourceComponent value={ word } />; 
    } 
    renderWordinput() { 
     return <WordinputComponent id={1} onChange={ this.onChange.bind(this) }/>; 
    } 
    onChange(id, value) { 
     const word = this.state.words[this.state.index]; 
     if (word == value) { 
      alert('yes'); 
      var nextIndex = (this.state.index == this.state.words.count-1)? 0 : this.state.index+1; 
      this.setState({ words:this.state.words, index:nextIndex }); 
     } 
    } 
    render() { 
     return (
     <div className="index"> 
      <div>{this.renderWordsource()}</div> 
      <div>{this.renderWordinput()}</div> 
     </div> 
    ); 
    } 
} 

// the input component 
class WordinputComponent extends React.Component { 
    constructor(props) { 
     this.state = { text:''} 
    } 
    handleChange(event) { 
     var text = event.target.value; 
     this.props.onChange(this.props.id, text); 
    } 
    render() { 
     return (
     <div className="wordinput-component"> 
      <input type="text" onChange={this.handleChange.bind(this)} /> 
     </div> 
    ); 
    } 
} 

보기 ... 여기 입력 요소 자체를 삭제하는 방법에 대한 몇 가지 답변을 본 적이 있지만 그 입력이 선택되는 경우이기 때문에, 그것을 포함하는 구성 요소에서 선택을 취소해야합니다 alert('yes')? 그것이 내가 value을 깨끗하게해야한다고 생각하는 곳이지만, 그것은 매개 변수이기 때문에 이해가되지 않습니다. 실제로는 구성 요소의 상태가 아닙니다. 구성 요소 자체를 변경 함수에 전달해야합니까? 어쩌면 나는 그것의 상태를 바꿀 수 있었지만, 그것은 디자인에 대한 잘못된 생각처럼 들린다.

답변

5

이렇게하는 일반적인 두 가지 방법은 부모의 상태를 통해 값을 제어하거나 값을 지우는 ref를 사용하는 것입니다. 두

의 추가 예는 첫 번째는 두 번째 상위 성분과 제어 입력 필드의 상태로 사용이 그것을

class ParentComponent1 extends React.Component { 
 
    state = { 
 
    input2Value: '' 
 
    } 
 
    clearInput1() { 
 
    this.input1.clear(); 
 
    } 
 
    clearInput2() { 
 
    this.setState({ 
 
     input2Value: '' 
 
    }); 
 
    } 
 
    handleInput2Change(evt) { 
 
    this.setState({ 
 
     input2Value: evt.target.value 
 
    }); 
 
    } 
 
    render() { 
 
    return (
 
     <div> 
 
     <ChildComponent1 ref={input1 => this.input1 = input1}/> 
 
     <button onClick={this.clearInput1.bind(this)}>Clear</button> 
 
     <ChildComponent2 value={this.state.input2Value} onChange={this.handleInput2Change.bind(this)}/> 
 
     <button onClick={this.clearInput2.bind(this)}>Clear</button> 
 
     </div> 
 
    ); 
 
    } 
 
} 
 

 
class ChildComponent1 extends React.Component { 
 
    clear() { 
 
    this.input.value = ''; 
 
    } 
 
    render() { 
 
    return (
 
     <input ref={input => this.input = input} /> 
 
    ); 
 
    } 
 
} 
 

 
class ChildComponent2 extends React.Component { 
 
    render() { 
 
    return (
 
     <input value={this.props.value} onChange={this.props.onChange} /> 
 
    ); 
 
    } 
 
} 
 

 
ReactDOM.render(<ParentComponent1 />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
을 취소하는 (REF)를 사용 을 취소 하위 구성 요소의 기능을 걸고

+0

이 매우이다 도움이! 정말 고마워. 당신이 다른 사람의 충고에 대해 논평 해 주시겠습니까? 아이의 상태를 유지하는 것이 결국에는 자식 세부 정보를 가진 부모를 부 풀릴 것 같지만, 레퍼런스에서 함수를 호출하는 것이 반응으로 선언하는 것처럼 보이지 않는 것처럼 보입니다. – user1272965

+0

나는 단순한 유즈 케이스에 대해 ref를 사용하는 것이 좋고 아마도 바람직하다고 생각한다. 부모에게서 아이의 가치를 바꿀 필요가 없을 때도 좋습니다. 반면 부모로부터 값을 변경해야 할 때 상위 또는 일부 저장소 구성 요소에 상태가있는 것이 좋습니다. (그렇지 않으면 자식 값을 변경하는 경우 자식에 다른 메서드를 작성해야합니다.) 폼을 제출해야 할 때 유효성 검사를 수행하는 데 필요한 모든 값에 액세스 할 수있는 부모 구성 요소가 있어야하는 경우에도 유용합니다. – noveyak

0

비슷한 문제가 있습니다. 여러 필드가 포함 된 양식을 정리하고 싶습니다.

@noveyak의 two solutions이 정상적으로 작동하는 동안 다른 아이디어를 공유하고 싶습니다. 부모와 자식 간의 책임을 나눌 수있는 기능을 제공합니다. 부모는 언제 양식을 지우는지 알고 항목에 심판을 사용하지 않고 그에 반응하십시오.

아이디어는 수정 카운터를 사용하여 지우기를 누를 때마다 증가하고 하위의이 카운터의 변경에 반응하는 것입니다.

아래 예제에서는 지우기 버튼에 반응하는 3 명의 아주 간단한 아이들이 있습니다.

class ParentComponent extends React.Component { 
 
    state = {revision: 0} 
 
    clearInput =() => { 
 
    this.setState((prev) => ({revision: prev.revision+1})) 
 
    } 
 
    render() { 
 
    return (
 
     <div> 
 
     <ChildComponent revision={this.state.revision}/> 
 
     <ChildComponent revision={this.state.revision}/> 
 
     <ChildComponent revision={this.state.revision}/> 
 
     <button onClick={this.clearInput.bind(this)}>Clear</button>   
 
     </div> 
 
    ); 
 
    } 
 
} 
 
class ChildComponent extends React.Component { 
 
    state = {value: ''} 
 
    componentWillReceiveProps(nextProps){ 
 
    if(this.props.revision != nextProps.revision){ 
 
     this.setState({value : ''}); 
 
    } 
 
    } 
 
    saveValue = (event) => { 
 
    this.setState({value: event.target.value}) 
 
    } 
 
    render() { 
 
    return (
 
     <input value={this.state.value} onChange={this.saveValue} /> 
 
    ); 
 
    } 
 
} 
 
ReactDOM.render(<ParentComponent />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

편집 : 난 그냥 정신에서 다소 유사하다이 아름답게 간단한 solution with key 우연히 한 (당신이 전달할 수있는 부모의 revision 아이가 key 등)

관련 문제