React-bootstrap 调用外部组件的方法

5
我正在使用react-bootstrap来启动一个模态表单。
为了做到这一点,我创建了一个模态组件PopupForm,一个表单组件ProductForm和一个产品组件,在产品组件中我调用了。
<ModalTrigger 
    modal={<PopupForm form={<ProductForm ref="pform" data={this.props.prod_data} />}/>}>
       <Button bsStyle='primary' bsSize='small' style={{marginRight:'5px'}} >
            <span className="glyphicon glyphicon-pencil" />
       </Button>
</ModalTrigger>

弹出表单:
var PopupForm = React.createClass({
    render: function(){
        return (
            <Modal {...this.props} bsStyle='primary' 
                   style={{width:200}} title='Edition' animation={false}>
            <div className='modal-body'>
                {this.props.form}
            </div>
            <div className='modal-footer'>
              <Button onClick={this.props.form.submit()}>Editer</Button>
              <Button onClick={this.props.onRequestHide}>Close</Button>
            </div>
          </Modal>
        )
    }
});

在这个 onClick 编辑器中,我想调用 ProductForm 组件的 submit 方法,将 ProductForm 组件作为属性 form 传递给 PopupForm,并像这样显示它 {this.props.form},但我无法调用方法 {this.props.form.submit()}。实际上,我想使用模态框按钮来触发 ProductForm 方法,如果不可能的话,我会在 ProductForm 中使用提交按钮。
这是我的 ProductForm
var ProductForm = React.createClass({

    componentDidMount: function() {
        this.props.submit = this.submit;
    },


    getInitialState: function () {
        return {canSubmit: false};
     },

    enableButton: function () {
      this.setState({
        canSubmit: true
      });
    },
    disableButton: function () {
      this.setState({
        canSubmit: false
      });
    },
    submit: function (model) {
      alert('ok');
    },
    render: function () {
      return (

            <Formsy.Form className="" name="test" onValidSubmit={this.submit} onValid={this.enableButton} onInvalid={this.disableButton}>


              <CsInput value={this.props.data.name} 
                label="Nom" id="product_name" 
                name={this.props.data.name}
                validations={{matchRegexp: /^[A-Za-z0-9]{1,30}$/}} 
                validationError={validations_errors[1]} required/>



              {/*<button type="submit" disabled={!this.state.canSubmit}>Submit</button>*/}


            </Formsy.Form>
      );
    }
  });

提前感谢。
1个回答

2
如果您有嵌套的组件,可以像这样调用另一个组件的函数:
Child:
var Component1 = React.createClass({
    render: function() {
        return (
            <div><button onClick={this.props.callback}>click me</button></div>
        )
    }
})

父级元素:

var Component2 = React.createClass({
    doSomethingInParent: function() {
        console.log('I called from component 2');
    },
    render: function() {
        return (
            <div><component1 callback={this.doSomethingInParent} /></div>
        )
    }
})

同样适用于您的情况。由于您的代码不太清晰,我无法帮助您处理代码本身。如果您感到混乱,请以分层的方式发布您的整个代码,这样更易读。

这是“React方式”来完成它。任何需要被多个组件共享的内容(如操作或数据)都应该来自于一个共同的父组件。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接