简体   繁体   中英

The same component render two times

I want render the same component instance of <Child /> two times in <Parent /> component.

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>
  )
}

Is it possible to do?

You are treating component as value. Just change your parent.js as follow.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM