React.createRef() を使用して dom の 1 つの要素にアクセスする方法を知っています。しかし、createRef を使用して 2 つの異なる要素にアクセスしたいと考えています。複数の要素に動的にアクセスするためのスタックオーバーフローの例を見てきましたが、理解できません。ボタンのスパンタグ onClick の背景色を変更したい単純なコードをここに添付しています。これに続いて、ドキュメントを反応させました。私がここで間違っていることを教えてください。
class TodoApp extends React.Component {
constructor(props) {
super(props)
// this.myRef = React.createRef();
this.textInput = null;
this.state = {
fname:""
}
}
setTextInputRef = element => {
console.log("element",element);
this.textInput = element;
};
green = () =>{
console.log("green ",this.textInput);
/* this.textInput.current.style.backgroundColor = "green"; */
this.textInput.style.backgroundColor = "green";
}
red = () =>{
console.log("red ",this.textInput);
/* this.textInput.current.style.backgroundColor = "red"; */
this.textInput.style.backgroundColor = "red";
}
render() {
return (
<div>
{/*
<span id="green" ref={input => { this.setTextInputRef = input; }}>Green</span><br/>
<span id="red" ref={input => { this.setTextInputRef = input; }}>Red</span><br/>
*/}
<span id="green" ref={this.setTextInputRef}>Green</span><br/>
<span id="red" ref={this.setTextInputRef}>Red</span><br/>
<button onClick={this.green}>For Green</button><br/>
<button onClick={this.red}>For Red</button><br/>
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
上記のコードで、ユーザーが btn をクリックすると、それぞれのスパンの色が変更されます。
どんな助けでも大歓迎です。