2016-06-22 6 views
1

좋아요. ReactJS를 수정하고 간단한 예제로 작업하고 있습니다. 모든 것이 잘 작동하며 이미 생산성이 향상되었다고 느낍니다. 이제 앱 이름을 사용하고 Enter 키 누름이 감지되면 콘솔에 기록하는 간단한 React 예제를 작성하고 있습니다. 입력 상자에 앱 이름을 입력하고 엔터 키를 누를 때까지 콘솔 로그에서 볼 수있는 것은 입력 값이 아니라 "정의되지 않은"값입니다. 전체 JS 코드는 다음과 같습니다.React 구성 요소의 소품에 액세스

"use strict"; 

var InputText = React.createClass({ 
    render() { 
     return <div><p>Please input the app name you wish to access:</p></div> 
    } 
}); 

var InputBox = React.createClass({ 
    onKeyPress(e) { 
     if (e.key === 'Enter') { 
     console.log(this.props.value); 
     } 
    }, 
    render() { 
     return <input type="text" onKeyPress={this.onKeyPress}></input> 
    } 
}); 

var AppForm = React.createClass({ 
    render() { 
     return <div class="appForm"> 
      <InputText /> 
      <InputBox /> 
     </div> 
    } 
}); 

var App = React.createClass({ 
    render() { 
     return <AppForm /> 
    } 
}); 

ReactDOM.render(
    <App />, 
    document.getElementById("container") 
); 

답변

1

값을 입력 상자 구성 요소에 전달하지 않기 때문입니다.

당신은 이벤트

var InputBox = React.createClass({ 
    onKeyPress(e) { 
     if (e.key === 'Enter') { 
     console.log('InputBox Value: ' + e.target.value); 
     } 
    }, 
    render() { 
     return <input type="text" onKeyPress={this.onKeyPress}></input> 
    } 
}); 

jsfiddle

에서 값을 가져 오거나 상태 값을 저장하고 거기에서 그것을 얻을 수 있습니다.

var InputBox = React.createClass({ 
    onKeyPress(e) { 
     if (e.key === 'Enter') { 
     console.log('InputBox Value: ' + this.state.value); 
     } 
    }, 
    render() { 
     return <input type="text" onKeyPress={this.onKeyPress} onChange={(e) => this.setState({value: e.target.value})}></input> 
    } 
}); 

jsfiddle

1

소품을 전달하지 않았습니다. 실제로이 응용 프로그램 :

하지만 당신이 정말로 원하는 것은 입력 상자에서 값이 어디 전달에는 소품이없는이

같은 소품을 통과한다. 그래서 React에서 당신은 참조를 만들 것입니다. 신속하고 더러운 예를 들어 나는

<input type="text" className="inputClass" style={inputStyles} ref={(c) => ctx._input = c} /> 

ctx={} 지금 내 구성 요소에 내가

ctx._input.value 

CONSOLE.LOG 것과 입력 한 값을 참조 할 수있는 글로벌 컨텍스트 객체를 가지고 있고 그것은 모두 잘되어야합니다.

1

사용 심판 이벤트 전자를 사용하는 값을 얻기 위해 입력 상자

"use strict"; 

var InputText = React.createClass({ 
    render() { 
     return <div><p>Please input the app name you wish to access:</p></div> 
    } 
}); 

var InputBox = React.createClass({ 
    onKeyPress(e) { 
     if (e.key === 'Enter') { 
     console.log(this.refs.textbox.value); 
     } 
    }, 
    render() { 
     return <input type="text" onKeyPress={this.onKeyPress} ref = 'textbox'></input> 
    } 
}); 

var AppForm = React.createClass({ 
    render() { 
     return <div class="appForm"> 
      <InputText /> 
      <InputBox /> 
     </div> 
    } 
}); 

var App = React.createClass({ 
    render() { 
     return <AppForm /> 
    } 
}); 

ReactDOM.render(
    <App />, 
    document.getElementById("container") 
); 

JSFIDDLE

또 다른 방법의 가치를 것입니다 액세스 할 수 012로. 소품은 실제로 소품을 InputBox 구성 요소에 전달하지 않기 때문에 작동하지 않습니다.

관련 문제