[英]TypeError: Cannot read property 'target' of undefined for event.target in event listener
[英]TypeError: Cannot read property 'style' of null on event.target
我將event.target
嵌套在自定義函數上。
_buttonPublish = (event) => {
var TreeMap = this.state.TreeMap;
this.state.ObjectTree.forEach(item => {
TreeMap.push(this._parseItemToTreeMap(item));
this.setState({
TreeMap: TreeMap,
publish: true
}, () => {
event.target.style.top = item.position.y;
event.target.style.left = item.position.x;
});
});
}
<button type="button" onClick={(e) => this._buttonPublish(e)} style={{width: 200, height: 100}}>
Publish!
</button>
為什么樣式是未定義的?
為了在setState
的異步上下文中使用 React 的合成事件,我必須對其調用event.persist()
。 這允許您訪問setState
回調中的event
:
// this function just simulates the properties you seem to have on `ObjectTree`'s elements function makeTreeItem() { function randint(min, max) { return Math.round(Math.random() * Math.abs(max - min) + min); } return { position: { x: `${randint(0, 100)}px`, y: `${randint(0, 100)}px` } }; } class App extends React.Component { constructor() { super(); this.handleClick = this.handleClick.bind(this); this.state = { ObjectTree: [ makeTreeItem(), makeTreeItem(), makeTreeItem(), makeTreeItem() ] }; } handleClick = event => { event.persist(); this.state.ObjectTree.forEach(item => { this.setState( { publish: true }, () => { // access and adjust the event `target`'s position event.target.style.top = item.position.y; event.target.style.left = item.position.x; } ); }); }; render() { return ( <div style={{ position: "relative" }}> <button onClick={this.handleClick} style={{ position: "absolute" }}> Publish! </button> </div> ); } } ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
絕對感覺這里仍然缺少關於您想要的結果的東西,即您根據state.ObjectTree
數組中最后一個元素的位置屬性設置按鈕的位置:在我看來,這是一個非常令人困惑的 UI 模式,但是至少您現在應該能夠訪問event
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.