现在,我正在处理一个表示表单输入字段的Input组件。我希望它具有通用性(例如文本,日期和数字)。到目前为止的问题是,我不知道如何将未知属性直接传递给我的输入元素,这是代码:

import React, { Component } from 'react'
import PropTypes from 'prop-types'

class Input extends Component {
    render () {
      let required = false
      if (this.props.required) {
        required = true
      }
      return (
        <div className='form-group'>
          <label>{ this.props.label }</label>
          <input
            type={this.props.type}
            name={this.props.name}
            value={this.props.value}
            placeholder={this.props.placeholder}
            className={this.props.className}
            onChange={this.props.handleChange}
            {this.props.attrs}  // error here
            required = {required}
          />
        </div>
      )
    }
}

Input.propTypes = {
  attrs: PropTypes.string,
  label: PropTypes.string.isRequired,
  type: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  value: PropTypes.string.isRequired,
  placeholder: PropTypes.string,
  className: PropTypes.string,
  handleChange: PropTypes.func.isRequired,
  required: PropTypes.bool
}

Input.defaultProps = {
  type: 'text',
  required: true
}

export default Input

当我将this.props.attrs直接插入input元素时,React会拒绝它,但我不知道该怎么做...

为什么我甚至需要this.props.attrs?

我不知道将来可能要使用哪种输入类型。假设我要输入数字。在这种情况下,我可以在this.props.attrs中存储min = '1' max = '100'字符串。

因此,当我将this.props.attrs传递给组件时,我想获得如下输入:
<input ... min = '1' max = '100' ... />

最佳答案

您应该使用object spread {...this.props.attrs}请注意,这是一个提案,目前处于阶段3。

这是一个正在运行的示例:

class MyInput extends React.Component {
  render() {
    const { title, ...restOfProps } = this.props;
    return (
      <div>
        <label>{title}</label>
        <input {...restOfProps} />
      </div>
    );
  }
}

ReactDOM.render(<MyInput title="password" type="password" style={{border:'3px solid green', margin:'0 5px'}} />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

07-24 09:49
查看更多