React
HTML
<div id="app"></div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
.done {
color: rgba(0, 0, 0, 0.3);
text-decoration: line-through;
}
input {
margin-right: 5px;
}
React
/** ランダムな文字色、背景色のCSSスタイルを返す関数。色を変えてレンダリングが起きたことを分かりやすくします */
const makeRandomColorStyle = () => {
const getColor = () => Math.floor(Math.random() * 255);
return {
color: `rgb(${getColor()},${getColor()},${getColor()})`,
backgroundColor: `rgb(${getColor()},${getColor()},${getColor()})`,
};
};
/** ここから下が変更点です */
/**
* input 要素のラッパー関数です。
* 取り扱う値をインデックスや ID といった識別子付きオブジェクトである listItem で受け取り、
* onChange の際にはそれも返します。
*/
const AppInput = React.memo(({v, listItem, onChange}) => {
return <input style={makeRandomColorStyle()} type="text" value={v}
onChange={(e) => onChange(e, listItem)}/>
})
class LittleRerender extends React.Component {
constructor(props) {
super(props);
this.state = {
// 配列で入力欄の値を state として保持します
// index を id として持つようにしています。
// これにより配列内の要素単独でも何番目のどの要素かがわかります
inputList: [
{id: 0, v: 1},
{id: 1, v: 2},
{id: 2, v: 3},
]
};
this.handleChange = this.handleChange.bind(this)
}
/**
* 起きた変更を index 番目の要素に適用して state を更新します。
* 今度は要素自体の持つ id プロパティを用いて変更するべき場所を決めています。
* これにより、map メソッド経由で決まる index を渡されなくても特定の要素を更新できます
*/
handleChange(e, listItem) {
const inputList = [...this.state.inputList];
inputList[listItem.id].v = e.currentTarget.value;
this.setState({
inputList
})
}
render() {
return <div>
{this.state.inputList.map((listItem, i) => (<div key={i}>
{/* 入力欄の配列を元に input 要素を並べています。 */}
{/* アロー関数を使っていた場所がただの this.handleChange で済むようになりました */}
<AppInput v={listItem.v} listItem={listItem} onChange={this.handleChange}/>
</div>))}
</div>
}
}ReactDOM.render(<LittleRerender />, document.querySelector("#app"))