Reactjs 在组件上自动传递道具
我已经创建了一个Reactjs 在组件上自动传递道具,reactjs,react-props,react-component,Reactjs,React Props,React Component,我已经创建了一个Input组件,我已经使用样式化组件对其进行了样式化。我现在将该输入组件与Formik一起使用。我希望能够自动设置onChange、onBlur和值道具,而不必每次都设置它们(如使用Formik字段组件) 也就是说,现在这就是我的组件在使用时的外观: <Input name="firstName" onBlur={handleBlur} onChange={handleChange} value={values.firstName} /> 输入内容组
Input
组件,我已经使用样式化组件对其进行了样式化。我现在将该输入组件与Formik
一起使用。我希望能够自动设置onChange
、onBlur
和值
道具,而不必每次都设置它们(如使用Formik字段
组件)
也就是说,现在这就是我的组件在使用时的外观:
<Input
name="firstName"
onBlur={handleBlur}
onChange={handleChange}
value={values.firstName}
/>
输入内容组件
形似
{
常数{
车把,
handleChange,
价值观
}=道具
返回(
提交
)
}}
initialValues={{firstName:''}
validationSchema={validationSchema}
/>
我认为这不是一个好主意。但您可以做的是创建并包装它
// lasyWrapper.js
export function lazyWrapper(Input) {
return LazyWrapper extends React.Component {
render() {
return (
<Input
{...this.props}
name={this.props.name}
onBlur={this.props.handleBlur}
onChange={this.props.handleChange}
value={this.props.values[this.props.name]}
/>
)
}
}
}
// Input.js
export default lazyWrapper(Input)
// use somewhere
<Input
name="firstName"
{...this}
/>
//lasyWrapper.js
导出函数lazyWrapper(输入){
返回LazyWrapper.Component{
render(){
返回(
)
}
}
}
//Input.js
导出默认lazyWrapper(输入)
//在某处使用
但这确实是一个不好的想法。我担心没有办法解决这个问题,即使你自己制作自定义组件,你也需要传递适当的道具,另一个选择是使整个表单成为一个不受控制的组件。@Rohit据我所知,Formik的
字段
组件可以。我认为他们使用con文本-但我不知道怎么做。哦,上下文哈?还没有真正跟上最新的react功能。正如我提到的,不受控制的组件也是一个选项。我想保持这是一个受控制的组件。你还需要传递道具。
export const Input = props => {
const {
forId,
name,
placeholder,
} = props
const titleCase = startCase(name)
return (
<InputBase {...props}>
<InputSection>
<InputContent
id={forId ? forId : name}
placeholder={placeholder ? placeholder : titleCase}
type="text"
{...props}
/>
</InputSection>
</InputBase>
)
}
export const InputContent = styled.input`
// STYLES
`
<Formik
render={props => {
const {
handleBlur,
handleChange,
values,
} = props
return (
<Form>
<Input
name="firstName"
onBlur={handleBlur}
onChange={handleChange}
value={values.firstName}
/>
<Button type="submit">Submit</Button>
</Form>
)
}}
initialValues={{firstName: ''}
validationSchema={validationSchema}
/>
// lasyWrapper.js
export function lazyWrapper(Input) {
return LazyWrapper extends React.Component {
render() {
return (
<Input
{...this.props}
name={this.props.name}
onBlur={this.props.handleBlur}
onChange={this.props.handleChange}
value={this.props.values[this.props.name]}
/>
)
}
}
}
// Input.js
export default lazyWrapper(Input)
// use somewhere
<Input
name="firstName"
{...this}
/>