简体   繁体   English

另一个组件中的 Reactjs Ref

[英]Reactjs Ref in another component

I'm making a button generator using react.我正在使用 react 制作按钮生成器。 在此处输入图片说明 So, when user click get code, it'll get outerHTML of Green Button(Whatsapp button) .因此,当用户单击获取代码时,它将获取Green Button(Whatsapp button) 的外层HTML But in react, what i know to get element is using ref.但是在反应中,我所知道的获取元素是使用 ref。 the problem is the Green button different components with Get The Code button.问题是绿色按钮获取代码按钮不同的组件。
Here is my code.这是我的代码。

import React from 'react';

import ButtonCanvas from '../containers/buttonCanvas';
import ButtonGroup from './buttonGroup';

import SectionHeading from '../../commons/SectionHeading';
import TabComponent from '../../commons/tabs';

const ButtonBuilder = () => {
  const items = [
    {
      name: 'HTML Code',
      content: "Result 1",
    },
    {
      name: 'JS Code',
      content: 'Result 2',
    },
    {
      name: 'CSS Code',
      content: 'Result 3',
    },
  ];
  return (
    <div>
      <SectionHeading headingText="Button Setup" />
      <ButtonCanvas />
      <ButtonGroup />
      <TabComponent
        tabList={items}
        activeTab={items[0].name}
        tabStyle="is-medium"
        additionalClass="is-fullwidth"
      />
    </div>
  );
};

export default ButtonBuilder;

ButtonCanvas is Green Button Component and ButtonGroup is component of Get The Code Button ButtonCanvas绿色按钮组件, ButtonGroup获取代码按钮的组件
So, when user click ButtonGroup it will get ref value from ButtonCanvas and place it to const items因此,当用户单击ButtonGroup ,它将从ButtonCanvas获取 ref 值并将其放置到const items

one way to pass a value of the ref from the <ButtonCanvas /> component is to save the value of the ref into a state in your parent component and then passing the state to the other child of your app like this <ButtonCanvas {...this.state} /> then you can access the state from your child element as a props you can find in this link a basic example on how to pass data between element<ButtonCanvas />组件传递 ref 值的一种方法是将 ref 值保存到父组件中的状态中,然后将状态传递给应用程序的另一个子组件,如下所示<ButtonCanvas {...this.state} />然后你可以从你的子元素访问状态作为道具你可以在这个链接中找到一个关于如何在元素之间传递数据的基本示例

https://gist.github.com/sebkouba/a5ac75153ef8d8827b98 https://gist.github.com/sebkouba/a5ac75153ef8d8827b98

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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