[英]Pass values to another component in React Final Form
使用向導表單示例創建具有當前輸入值的組件。 奇怪的是,組件是相同的,但是當Slider
組件返回空對象時,只有Wizard
組件返回具有初始值的對象。 最重要的是,是否可以保持值的更新?
class Slider extends React.Component {
constructor(props) {
super(props)
this.state = {
page: 0,
values: props.initialValues || {}
}
}
render() {
const { values } = this.state
console.log(values);
return (
<div></div>
)
}
}
更新
我的問題是輸入類型范圍樣式: https : //codesandbox.io/s/w65rq7ok4w 。 嘗試創建一個將返回div並具有動態變化寬度的組件,該寬度將取決於輸入類型范圍值,例如具有CSS梯度的Input Range進度
您需要創建所有包含狀態的子表單的parent component
。 這是示例:
class Slider extends React.Component {
constructor(props) {
super(props)
this.state = {
page: 0,
values: props.initialValues || {
employed: false,
otherKey: "otherValue"
}
}
this.handleUpdate = this.handleUpdate.bind(this);
this.nexPage = this.nexPage.bind(this);
}
handleUpdate(nextValues) {
this.setState({ values: { ...this.state.values, nextValues} });
}
nextPage() {
this.setState({ page: this.state.page + 1 });
}
renderForm(){
const { values } = this.state;
switch(page) {
case 3: return <ThirdForm {...values}/>;
case 1: return <AnotherForm {...values} />;
default: return <FirstForm {...values}/>;
}
}
render() {
const { values } = this.state
console.log(values);
return (
<div>
{this.renderForm()}
</div>
)
}
}
因此,您的值就地存儲,並且只能通過handleUpdate
方法的父級組件進行更改。
當子組件的onChange
方法觸發時,父組件會將其數據傳遞給子組件。 這是示例(其他形式相同...):
class FirstForm extends React.Component {
handleChange(e) {
this.props.handleUpdate({ [e.target.name]: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
this.props.nextPage();
}
render() {
const { value1 } = this.props;
return(
<form onSubmit={this.handleSubmit.bind(this)}>
<input name="value1" value={value1} onChange={this.handleChange.bind(this)}/>
</form>
);
}
}
設置屬性name
是輸入的value
的鍵和value
,並將其通過子級handleChange
方法和父級handleUpdate
方法傳遞給父級組件。
提交時,您需要通過父方法nextPage
來更改頁面。
對於輸入寬度樣式(范圍:最小[0]最大[100]):
render() {
const { values: { rangeValue } } = this.state;
return(
<div style={{ width: `${rangeValue}%` }}></div>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.