javascript - 带有样式组件的不受控制的子组件

标签 javascript reactjs styled-components

我正在尝试创建一个可重用的组件,该组件是不受控制的输入。通常这工作正常,但我无法让它与应用于子组件的 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.

所以只需更改 refinnerRef在您的<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/

相关文章:

javascript - 如何从对象文字数组中切片数组?

php - 提交表格给自己

javascript - 是否可以检查用户是否有摄像头和麦克风以及是否已使用 Javascript 授予权限?

javascript - React json渲染猫图像

django - 为什么我的 React-Django 应用程序检测不到静态文件?

javascript - 如何在 react 组件中使用样式组件

javascript - 动态 iframe 高度取决于

reactjs - 如何正确缩放页面上的 Dygraph?

css - 在 React 中切换翻转卡片

javascript - 提交空搜索请求时出现错误 'TypeError: Cannot read property ' map' of undefined'