КОНТЕКСТДинамически Добавить Реагировать компоненты
Я пытаюсь динамически добавлять поля ввода в среагировать компонента в то же время отслеживании состояний в родительском компоненте (в дальнейшем вызвать метод, используя их).
ПРОБЛЕМА
Не знаете, как идти об этом:
- Без необходимости определить фиксированное число состояний (
urlpath1
,urlpath2
и т.д.) в родительском компоненте. - Без определения фиксированного количества компонентов детского компонента
<Input/>
.
Это мой родительский компонент - это нужно, чтобы захватить государство (или значение) входные элементы детей/внуков компонентов, независимо от того, сколько таких <Input>
полеев у меня есть.
import AddConditionSelect from './AddConditionSelect.jsx';
class AddConditionDashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
//Form Steps States
step: 1,
//AddConditionSelect States
conditionTitle: '',
conditionType: ''
};
// bind the context for the user input event handler
// so we can use `this` to reference `AddConditionDashboard`
this.onUserInputChange = this.onUserInputChange.bind(this);
this.onUserClick = this.onUserClick.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
//TODO: REFACTOR - Can we refactor both these events into one to be used?
onUserInputChange(event) {
this.setState({
conditionTitle: event.target.value
});
}
onUserClick(event) {
this.setState({
conditionType:event.target.value
});
}
onSubmit(event) {
event.preventDefault;
const {create, segmentId} = this.props;
const conditionTitle = this.state.conditionTitle;
const conditionType = this.state.conditionType;
create(conditionTitle, conditionType, segmentId);
//TODO: CALLBACK IF STATEMENT - Check with a callback function if create ran sucessfully, only then do nextste();
if (conditionType == 'urlPath') {
this.setState({
step: 21
});
} else if (conditionType == 'timeOnSite') {
this.setState({
step: 22
});
};
}
render() {
const {error, segmentId} = this.props;
switch (this.state.step) {
//SELECT CONDITION
case 1: return (
<div>
{error ? <Message inverted={true} rounded={true} theme="error">{error}</Message> : null}
<AddConditionSelect
segmentId={segmentId}
onUserClick={this.onUserClick}
conditionTitle={this.state.conditionTitle}
onUserInputChange={this.onUserInputChange}
/>
<PanelFooter theme="default">
<Button
backgroundColor="primary"
color="white"
inverted={true}
rounded={true}
onClick={(event) => this.onSubmit(event)}
>
Next Step
</Button>
</PanelFooter>
</div>
);
//ADD URL PATH
case 21: return (
<div>
<AddConditionCURLPath 'something here' />
<PanelFooter theme="default">
<Button
backgroundColor="primary"
color="white"
inverted={true}
rounded={true}
onClick={(event) => this.onSubmit(event)}
>
Next Step
</Button>
</PanelFooter>
</div>
);
//ADD TIME ON SITE
case 22: return (
<div>
<AddConditionSomethignElse />
<PanelFooter theme="default">
<Button
backgroundColor="primary"
color="white"
inverted={true}
rounded={true}
onClick={(event) => this.onSubmit(event)}
>
Next Step
</Button>
</PanelFooter>
</div>
);
}//End switch
//end render
}
}
export default AddConditionDashboard;
Это мой ребенок компонент - здесь мне нужно динамически добавлять новые `поля, значения которых должны быть переданы в качестве родительского компонента.
class AddConditionCURLPath extends React.Component {
render() {
const {error} = this.props;
return (
<div>
<Panel theme="info">
{error ? <Message inverted={true} rounded={true} theme="error">{error}</Message> : null}
<Container>
Configure URL Path - What Pages A Visitor Needs to Visit to meet this conditino
<Divider />
<Input
value={this.props.urlPath}
label=""
type="text"
buttonLabel="Add Condition"
name="add_segment"
onChange={this.props.onUserInputChange}
placeholder="Condition Title"
/>
<Input
value={this.props.urlPath}
label=""
type="text"
buttonLabel="Add Condition"
name="add_segment"
onChange={this.props.onUserInputChange}
placeholder="Condition Title"
/>
<Button
backgroundColor="primary"
color="white"
inverted={true}
rounded={true}
onClick={(event) => this.addInputField(event)}
>
Add Another Input Field
</Button>
</Container>
</Panel>
</div>
);
}
}
export default AddConditionCURLPath;
Является ли это репост? Кажется, я помню это раньше. :) Вы используете 'redux' в своем приложении? Если это так, вы можете рассмотреть использование 'redux-form' для отслеживания состояния вашей формы и управления ею. – ctrlplusb
Не использовать 'Redux' в приложении. Сомневаюсь, что это репост, поскольку я просто наткнулся на эту проблему ... – Dan
Ах, тогда вам может быть повезло. Попробуйте найти stackoverflow для проблемы. Я почти уверен, что кто-то задал почти одинаковый вопрос. Я посмотрю, если это в моей истории. – ctrlplusb