모두 onchange
의 이벤트 리스너 또는 componentDidMount
(자세한 내용은 구현을위한 스 니펫 참조)을 추가 할 수 있습니다. 그러면 React 내부의 상태가 업데이트됩니다. 스 니펫은 주석으로 잘 설명되어 있습니다. 그것은 당신을 도울 것입니다!
class KeyTrace extends React.Component {
constructor(props) {
super(props)
this.setValueToState = this.setValueToState.bind(this)
this.state = {} //initial state
}
setValueToState(e) {
this.setState({
[e.target.id]: e.target.value //set the new value in the state as {[id]: [value]} pair
})
}
componentDidMount() {
const textareas = document.querySelectorAll('textarea') //finds all textarea in the DOM
const textareasArray = [...textareas] //convert the HTML Collection into array
textareasArray.forEach((el) => { //loop through the array
if (el.id === 'update') //add onchange listener for specific textareas (optional)
el.onchange = this.setValueToState //add a event listener
})
}
render(){
console.log(this.state)
return false
}
}
ReactDOM.render(<KeyTrace/>, document.getElementById('react'))
<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>
<div id="non-react">
Changes will be stored in react state
<br/>
<textarea id="update"></textarea>
<br/>Changes will not be stored in react state
<br/>
<textarea id="wont-update"></textarea>
<br/>
</div>
<div id="react"></div>
PS. blur
(텍스트 영역 외부를 클릭하십시오) onchange
이벤트를 발생시키는 텍스트 영역이 필요합니다. 그렇지 않으면 onchange
대신 onkeypress
을 사용할 수 있습니다.
글쎄, 중요한 것은'input' 또는'textarea' HTML이 그 확장자에 의해 사용 된'.value' 속성의 직접적인 변경에 대해 변경되지 않는다는 것입니다. text 요소라면'document.activeElement.value'를 정기적으로 폴링해야 할 것입니다. – wOxxOm
폴링은 나를위한 완벽한 해결책이 아닙니다. 다른 생각? – manish
글쎄, 이러한 확장 기능은'keydown'이나 다른 하드웨어 이벤트 직후에 값을 변경하기 때문에, 그것들을 듣고 한동안 폴링 한 다음 멈출 수 있습니다. – wOxxOm