首页 > 解决方案 > 发送函数 throw `spread operator` 不起作用,但添加了状态值

问题描述

我正在传递一个函数和一个状态值抛出spread运算符。中的state值更新html。但是当点击button函数时根本没有调用。

使用reactjs 中的运算符发送function给孩子的正确方法是什么?spread

这是我的代码:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class Counter extends React.Component {
  render() {

    return (
      <div>
        <div>{this.props.display}</div>
        <button onClick={this.props.fun}>+</button> //onclick not works!!
      </div>
    );
  }
}

class CounterParent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0 //added
    };
  }

  increase = () => { //not called
    this.setState({
      count: this.state.count + 1
    });
  };

  render() {

    let object = {
      display: this.state.count,
      func: this.increase
    };

    return (
      <div >
        <Counter {...object} />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<CounterParent />, rootElement);

标签: reactjsreact-native

解决方案


Counter组件中,您拼错了func名称。

class Counter extends React.Component {
  render() {

    return (
      <div>
        <div>{this.props.display}</div>
        <button onClick={this.props.func}>+</button>
      </div>
    );
  }
}

推荐阅读