同一组件渲染两次

时间:2019-04-26 06:17:24

标签: javascript reactjs

我想在<Child />组件中两次渲染<Parent />的同一组件实例

index.js

import React from 'react';
import { render } from 'react-dom';

import Parent from './Parent';

render(
  <Parent />,
  document.getElementById('root')
);

Parent.js

import React from 'react';
import Child from './Child';

const child = <Child />

export default () => {
  return (
    <>
      {child}
      {child}
    </>
  )
}

Child.js

import React, { useState } from 'react';

function generateRandomString() {
  return Math.random().toString();
}

export default () => {
  const [text, setText] = useState(generateRandomString());

  function onClickHandler() {
    setText(generateRandomString());
  }

  return (
    <div onClick={onClickHandler}>text: {text}</div>
  )
}

有可能吗?

1 个答案:

答案 0 :(得分:1)

您正在将组件视为价值。只需按照以下步骤更改您的parent.js。

import React from 'react';
import Child from './Child';
export default () => {
  return (
    <div>
     <Child/>
     <Child/>
    <div/>
 )
}