TypeError: Cannot read property 'style' of null on event.target

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