从另一个类在App.js中反映渲染表单

时间:2018-03-19 10:02:55

标签: reactjs

我为表单SearchForm.js

创建了简单的测试类
import React from 'react';
import ReactDOM from 'react-dom';

const formContainer = document.querySelector('.form-container')

class SeacrhForm extends React.Component {
    constructor(props) {
      super(props)

      this.state = {
       keywords: '',
       city: '',
       date: ''     
      }

      this.handleChange = this.handleChange.bind(this)
      this.handleSubmit = this.handleSubmit.bind(this)
     }

    render() {
        return ( 
            <form className='search-form' onSubmit={this.handleSubmit}>
                <h1>Say Hi!</h1>
            </form>
        )
    }
}

//ReactDOM.render(<SeacrhForm />, formContainer)

这是我的App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import './SearchForm.js';

class App extends React.Component {
  render() {
    return (
      <div className="form-container">Test     
      </div>

    );
  }
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './bootstrap.min.css';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

但我不明白如何在App.js中呈现我的表单?

2 个答案:

答案 0 :(得分:2)

在App.js中渲染SearchForm并将其导入为import { SearchForm } from './SearchForm.js';

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { SearchForm } from './SearchForm.js';

class App extends React.Component {
  render() {
    return (
      <div className="form-container">Test  
        <SearchForm />   
      </div>

    );
  }
}

export default App;

并在纠正拼写错误后从SeachForm文件中导出

class SearchForm extends React.Component {
    constructor(props) {
      super(props)

      this.state = {
       keywords: '',
       city: '',
       date: ''     
      }

      this.handleChange = this.handleChange.bind(this)
      this.handleSubmit = this.handleSubmit.bind(this)
     }

    render() {
        return ( 
            <form className='search-form' onSubmit={this.handleSubmit}>
                <h1>Say Hi!</h1>
            </form>
        )
    }
}

export { SearchForm}

答案 1 :(得分:0)

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import './SearchForm.js';

class App extends React.Component {
  render() {
    return (
      <div className="form-container">
        <SearchForm />
      </div>

    );
  }
}

export default App;