React组件在屏幕上打印两次

时间:2018-05-27 19:53:00

标签: javascript reactjs react-props

名为'Person'的My React组件在屏幕上打印两次,一次没有props&一次用道具。

//App.js

import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person'

class App extends Component {
  render() {
    return (
      <div className="App">
       <h1>Hello I am Arjun</h1>
          <Person>But What's The Language?</Person>
          <Person technology="React" syntax="JSX"/>
      </div>
    );
  }
}

export default App;

//Person.js

import React from 'react'

const person = (props) => {
    return (
        <div>
            <p>{props.children}</p>
            <p>The technology used is {props.technology} & the syntax 
            is {props.syntax}</p>
        </div>
    )
};

export default person

这是输出:

React Output

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

其他答案告诉你如何做到这一点并告诉主要原因。我会尝试再解释一下。您正在渲染组件两次,并且由于组件的结构,您有三条线。

首先渲染:

<Person>But What's The Language?</Person>

在这里,您将使用子项渲染组件。你的孩子在这里“但这是什么语言?”串。除了孩子,你不会传递任何其他道具。您的组件形状为:

<p>{props.children}</p>
<p>The technology used is {props.technology} & the syntax is {props.syntax}</p>

第一行来自儿童道具。第二行是你的段落与其他道具。因此,在第一个渲染中,您没有这些道具,因此technologysyntax呈现为空。

你的第二次渲染:

<Person technology="React" syntax="JSX"/>

这里你没有孩子。这意味着没有<Person>Child</Person>形状,只有<Person />对于这个渲染,你有其他道具。第三行来自此呈现,包含technologysyntax道具。因此,你没有任何儿童道具,第一行是空的。

答案 1 :(得分:0)

问题在于您实际上渲染了两次组件。您的<Person />组件中只应有一个App标记:

//App.js

import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person'

class App extends Component {
  render() {
    return (
      <div className="App">
       <h1>Hello I am Arjun</h1>
          <Person technology="React" syntax="JSX">But What's The Language?</Person>
      </div>
    );
  }
}

export default App;

答案 2 :(得分:0)

您正在渲染组件两次,以获得所需的输出,您可以执行以下操作:

//App.js

import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person'

class App extends Component {
  render() {
    return (
      <div className="App">
        <h1>Hello I am Arjun</h1>
        <Person technology="React" syntax="JSX">
          But What's The Language?
        </Person>
      </div>
    );
  }
}

export default App;

这样,您的组件会将其子项呈现为“但这是什么语言?”,并接收第二行的technologysyntax属性。