如何使用 redux 形式的 formValueSelector() 来访问按钮的值
How to use formValueSelector() of redux form to acces of the value of a button
我使用 redux-from 创建一些表单。
今天,我需要创建一个动态的表单。
更准确地说,当用户单击按钮时,会显示一些字段。
我在 documentation of redux-form 上找到了这个样本。
在此示例中,它是一个复选框。
我尝试用按钮做同样的事情,但它不起作用。
有什么办法可以使用按钮吗?
对我来说,这与复选框的逻辑相同
<Field
name="button"
id="button"
type='button'
component={renderButton}
/>
{ button &&
<div>
test
</div>
}
const selector = formValueSelector( 'testFrom' );
function mapStateToProps (state) {
const button = selector( state , 'button' );
return {
button ,
};
}
感谢您的帮助。
button
元素没有 value
属性,这就是为什么 selector(state, 'button')
return 没有。
将 onClick
处理程序添加到您的按钮,您可以在其中将任何值设置为表单组件的状态。并根据此值显示或隐藏其他字段。
class SelectingFormValuesForm extends React.Component {
constructor(props) {
super(props);
this.state = {
isEmailVisible: false
};
}
render() {
const {handleSubmit} = this.props;
const {isEmailVisible} = this.state;
return (
<form onSubmit={handleSubmit}>
{isEmailVisible &&
<Field
name="email"
component="input"
type="email"
placeholder="Email"
/>
}
<button type="button" onClick={this.onShowEmailFieldClick}>{isEmailVisible ? 'Hide' : 'Show'} email field</button>
</form>
);
}
onShowEmailFieldClick = () => {
this.setState(prevState => ({
isEmailVisible: !prevState.isEmailVisible
}));
};
}
我使用 redux-from 创建一些表单。
今天,我需要创建一个动态的表单。 更准确地说,当用户单击按钮时,会显示一些字段。
我在 documentation of redux-form 上找到了这个样本。 在此示例中,它是一个复选框。
我尝试用按钮做同样的事情,但它不起作用。
有什么办法可以使用按钮吗?
对我来说,这与复选框的逻辑相同
<Field
name="button"
id="button"
type='button'
component={renderButton}
/>
{ button &&
<div>
test
</div>
}
const selector = formValueSelector( 'testFrom' );
function mapStateToProps (state) {
const button = selector( state , 'button' );
return {
button ,
};
}
感谢您的帮助。
button
元素没有 value
属性,这就是为什么 selector(state, 'button')
return 没有。
将 onClick
处理程序添加到您的按钮,您可以在其中将任何值设置为表单组件的状态。并根据此值显示或隐藏其他字段。
class SelectingFormValuesForm extends React.Component {
constructor(props) {
super(props);
this.state = {
isEmailVisible: false
};
}
render() {
const {handleSubmit} = this.props;
const {isEmailVisible} = this.state;
return (
<form onSubmit={handleSubmit}>
{isEmailVisible &&
<Field
name="email"
component="input"
type="email"
placeholder="Email"
/>
}
<button type="button" onClick={this.onShowEmailFieldClick}>{isEmailVisible ? 'Hide' : 'Show'} email field</button>
</form>
);
}
onShowEmailFieldClick = () => {
this.setState(prevState => ({
isEmailVisible: !prevState.isEmailVisible
}));
};
}