我尝试创建动态反应组件,这样我就可以轻松调用代码的任何部分中的组件。这种组件的一个例子是模态形式。我正在使用react-bootstrap,我试图坚持使用他们的预定义组件,但我错过了一些东西。
我有一个Modal表单组件,它从我作为prop传入的数组动态创建输入。
我的组件层次结构如下所示:Crud> MODALFORM> InputField
这是我的代码:
crud.js.jsx
...
createModalSubmit(form) {
console.log(form);
$.ajax({
url: '/products.json',
type: 'POST',
data: {product: {
name: name
}},
success: (product) => {
this.setState({
product: {
name: ''
},
errors: {},
showModal: false
});
},
error: (product) => {
this.setState({errors: product.responseJSON.errors})
}
});
},
render: function() {
var ModalForm = app.ModalForm;
return (
<div>
<ModalForm
showModal={this.state.showModal}
headerText="My Modal"
formElements= {[{"name":"name"}]}
unloadModal={this.unloadModal}
buttonText="Add"
onClickHandler={this.createModalSubmit}
formErrors={this.state.errors}
/>
</div>
);
}
...
modal_form.js.jsx
...
render: function() {
var Modal = require('react-bootstrap').Modal;
var InputField = app.InputField
var formElementsCollection= this.props.formElements.map((formElement, i) => {
return (
<InputField
inputControlID={formElement.name}
inputLabel={formElement.name}
key={i}
/>
)
});
return (
<Modal
keyboard={true}
show={this.props.showModal}
onHide={this.props.unloadModal}
>
<Modal.Header closeButton>
<h3>
{this.props.headerText}
</h3>
</Modal.Header>
<Modal.Body>
<form>
{formElementsCollection}
<button type="button" className="btn btn-info btn-fill pull-right" onClick={() => this.props.onClickHandler(this)}>{this.props.buttonText}</button>
</form>
<div className="clearfix"></div>
</Modal.Body>
</Modal>
);
}
});
...
input_field.js.jsx
...
getValidationState() {
const length = this.state.value.length;
if (length > 10) return 'success';
else if (length > 5) return 'warning';
else if (length > 0) return 'error';
},
handleChange(e) {
this.setState({ value: e.target.value });
},
render: function() {
var FormGroup = require('react-bootstrap').FormGroup;
var ControlLabel = require('react-bootstrap').ControlLabel;
var FormControl = require('react-bootstrap').FormControl;
return (
<FormGroup
controlId={this.props.inputControlID}
validationState={this.getValidationState()}
>
<ControlLabel>{this.props.inputLabel}</ControlLabel>
<FormControl
type="text"
value={this.state.value}
placeholder={this.props.placeholderText}
onChange={this.handleChange}
/>
<FormControl.Feedback />
</FormGroup>
);
}
...
在切换到反应引导组件之前,当我仍然为我需要的每个模态明确创建单独的表单时,我会明确地调用&#39; ref&#39;每个输入元素的属性。从父母那里动态检索子元素值的最佳方法是什么?