react子组件怎么修改父组件的state

项目用了react和typescript,没有用redux

子组件:

//FormGenerator.tsx
<Form.Item>
   {this.renderAction()}
</Form.Item>

public renderAction = () => {
    if (!this.props.actions) return null

    const { validateBeforeSubmit } = this.props.formData
    return this.props.actions(this.props.form, validateBeforeSubmit || null)
  }

父组件:

public render() {
    return (
      <div>
        <FormGenerator
          layout="inline"
          formData={formLabel}
          onSubmit={this.handleSearch}
          actions={this.renderAction}
        />
        
        {this.renderTable()}
        <Modal
          title="添加"
          visible={this.state.addVisible}
          onOk={this.handleAddOK}
          onCancel={this.handleAddCancel}
        >
          <p>Some contents...</p>
          <p>Some contents...</p>
          <p>Some contents...</p>
        </Modal>
      </div>
    )
  }

  public renderAction() {
    return (
      <div>
        <Button type="primary" onClick={this.handleAdd.bind(this)}>添加主播</Button>
      </div>
    )
  }

public handleAdd = () => {
    this.setState({
      addVisible: true,
    });
  }

我用bind方法但是报错

Binds are forbidden in JSX attributes due to their rendering performance impact

请问有没有其他不用redux的方法

阅读 6.9k
2 个回答

可以父组件给子组件传递一个事件,子组件接收这个事件,调用它,就会触发父组件中的方法,可以改变父组件的state

子组件:

class Child extends React.Component {
    onClick = () => {
        this.props.setParentState()
    }
    render() {
      return <button onClick={this.onClick}>修改父组件state</button>
    }
}

父组件:

class Parent extends React.Component {
    state = {
        number: 3
    }
    setSelfState = () => {
        this.setState({
            number: 4
        })
    }
    render() {
      return <div>
          {this.state.number}
          <Child
              setParentState={this.setSelfState}
          />
      </div>
    }
}

这个报错是因为在 jsx 中对方法进行 bind 操作,推荐在 constructor 中对事件进行绑定。

不用 redux 也可以,用源生的 context api就行了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题