我正在尝试创建一个可重用的组件,该组件是不受控制的输入。通常这工作正常,但我无法让它与应用于子组件的 styled-components
一起使用(value
返回 undefined
)。 p>
class Parent extends Component {
handleSubmit = (event) => {
console.log(this.firstName.value)
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>First Name</label>
<UncontrolledInput
defaultValue={'fish'}
inputType='text'
name='firstName'
inputRef={(element) => {this.firstName = element}}
/>
<button type="submit">
Submit
</button>
</form>
)
}
}
const StyledInput = styled.input`
border: 3px solid;
`;
const UncontrolledInput = (props) => {
const {name, inputType, defaultValue, inputRef} = props;
return (
<StyledInput
name={name}
type={inputType}
defaultValue={defaultValue ? defaultValue : ''}
ref={inputRef}
/>
)
};
最佳答案
styled-components
将元素包装到 react 组件中。通过ref
prop 不会为您提供对 DOM 元素的引用,而是对包装组件的引用。
在 styled-components docs描述了如何获取底层 DOM 元素的引用:
Passing a ref prop to a styled component will give you an instance of the StyledComponent wrapper, but not to the underlying DOM node. This is due to how refs work. It's not possible to call DOM methods, like focus, on our wrappers directly.
To get a ref to the actual, wrapped DOM node, pass the callback to the innerRef prop instead.
所以只需更改 ref
至innerRef
在您的<StyledInput>
上组件:
const UncontrolledInput = (props) => {
const {name, inputType, defaultValue, inputRef} = props;
return (
<StyledInput
name={name}
type={inputType}
defaultValue={defaultValue ? defaultValue : ''}
innerRef={inputRef}
/>
)
};
这是一个working example .
关于javascript - 带有样式组件的不受控制的子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48160044/