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 要素のラッパー関数コンポーネントです */
const AppInput = React.memo(({v,onChange}) => {
return <input style={makeRandomColorStyle()} type="text" value={v} onChange={onChange}/>
})
/** 意図せぬ再レンダリングが起きる例のクラスコンポーネントです */
class SoManyRerender extends React.Component {
constructor(props) {
super(props);
// 配列で入力欄の値を state として保持します
this.state = {inputList: [1, 2, 3]};
this.handleChange = this.handleChange.bind(this)
}
/** 起きた変更を index 番目の要素に適用して state を更新します */
handleChange(event, index) {
const inputList = [...this.state.inputList];
inputList[index] = event.currentTarget.value;
this.setState({
inputList
})
}
render() {
return <div>
{this.state.inputList.map((v, i) => (<div key={i}>
{/* 入力欄の配列を元に input 要素を並べています。 */}
{/* ここでアロー関数を使って無名関数を定義しているのがまずいです */}
<AppInput v={v} onChange={(e) => this.handleChange(e, i)}/>
</div>))}
</div>
}
}
ReactDOM.render(<SoManyRerender />, document.querySelector("#app"))