componentDidMount内で下記のようにするとconsole.log内では上手くいくのですが、この値をsetStateして使うと上手くいかないです。
この値を使えるようにするにはどうしたらよいでしょうか?
他の書き方でもよいので要素の横幅をリアルタイムに取得したいです。
何卒よろしくお願いいたします.
jsx
1//マップ幅の取得 2 let map = document.getElementById("map"); 3 var lastInnerWidth = map.clientWidth; 4 window.addEventListener("resize", function() { 5 if (lastInnerWidth != map.clientWidth) { 6 lastInnerWidth = map.clientWidth; 7 } 8 let boxSize = (lastInnerWidth - 100) / 5; 9 console.log(lastInnerWidth); 10 console.log(boxSize); 11 });
jsx
1//TypeError: this.setState is not a functionになる 2let map = document.getElementById("map"); 3 var lastInnerWidth = map.clientWidth; 4 window.addEventListener("resize", function() { 5 if (lastInnerWidth != map.clientWidth) { 6 lastInnerWidth = map.clientWidth; 7 } 8 let boxSize = (lastInnerWidth - 100) / 5; 9 this.setState({ 10 mapWidth: lastInnerWidth, 11 boxWidth: boxSize 12 }); 13 console.log(this.state.mapWidth); 14 console.log(this.state.boxWidth); 15 });
回答1件
あなたの回答
tips
プレビュー