内のすべてまたは特定のテキストエリアのonchange
イベントリスナーを追加できます(実装についてはスニペットを参照)。 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'プロパティの直接の変更では変更されません。テキスト要素の場合、 'document.activeElement.value'を定期的にポーリングする必要があります。 – wOxxOm
ポーリングは私にとって完璧な解決策ではありません。他のアイデア? – manish
これらの拡張機能は 'keydown'や他のハードウェアイベントの直後に値を変更するので、それらを聞いてしばらくポーリングしてから停止することができます。 – wOxxOm