React render props.children在运行子级事件时失败(子级是组件)

时间:2019-06-23 22:11:46

标签: reactjs

我正在创建一个ReactJS包。我创建了一个名为Form的组件,其中包含一个普通形式。在App.js上调用它时,我在其上添加了名为TextField的组件。因此,App.js上的代码是:

import React, { Component } from 'react'

import { Form, TextField } from 'form2'
import './App.css'

export default class App extends Component {
  render () {
    return (
      <div>
        <Form>
          <TextField placeholder="Type your name..." />
          <TextField placeholder="Type your email..." />
        </Form>
      </div>
    )
  }
}

Form组件的代码为:

import React, { Component } from 'react'

class Form extends Component {
  constructor(props) {
    super(props)
    this.state = {
      values: {}
    }
  }

  renderChildren = () => {
    return this.props.children;
  };

  render() {
    return <form>
      { this.renderChildren() }
    </form>
  }
}

export default Form

这是mt TextField组件:

import React, { Component } from 'react'

class TextField extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: null,
    };
  }

  onChange = ({ target }) => {
    this.setState({ value: target.value });
  };

  render() {
    return <input onChange={this.onChange} {...this.props}>
      {this.state.value}
    </input>
  }
}

export default TextField;

当我在输入中键入内容时,问题就出现了,输入消失了,并在控制台上收到了此错误消息:

The above error occurred in the <input> component

还有这个

Uncaught Invariant Violation: input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.

1 个答案:

答案 0 :(得分:0)

更改:

  render() {
    return <input onChange={this.onChange} {...this.props}>
      {this.state.value}
    </input>
  }

收件人:

  render() {
    return <input defaultValue={this.state.value} onChange={this.onChange} {...this.props} />
  }

或(取决于您想要的行为):

  render() {
    return <input value={this.state.value} onChange={this.onChange} {...this.props} />
  }

现有代码试图将input的子级设置为{this.state.value}