我有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>
为什么样式未定义?
答案 0 :(得分:1)
为了在setState
的异步上下文中使用React的综合事件,我不得不在其上调用event.persist()
。这使您可以在event
回调中访问setState
:
// 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
。