简体   繁体   English

如何将数据从 vanilla JavaScript 传递到 React 功能组件

[英]How to pass data from vanilla JavaScript to React functional component

I'm trying to update (setState) a React functional component from within "regular" (vanilla) JavaScript.我正在尝试从“常规”(香草)JavaScript 中更新(setState)一个 React 功能组件。

I searched through StackOverflow but all the answers deal with passing data from React to (vanilla) JavaScript, and not the other way around.我搜索了 StackOverflow,但所有答案都涉及将数据从 React 传递到(香草)JavaScript,而不是相反。

Let's take the example from the docs :让我们以文档中的示例为例:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

To render it in JavaScript, I do:为了在 JavaScript 中渲染它,我这样做:

let example = ReactDOM.render(
    <Example />,
    document.getElementById('example-wrapper')
);

Now suppose I want to manually update the count from the vanilla JavaScript code, outside of react.现在假设我想在反应之外手动更新香草 JavaScript 代码的计数。 Like:喜欢:

function updateExampleCount(newCount) {
    example.setCount(newCount);   // ???
}

I can't access the component state, as setCount is a private variable inside the function, and example returned from render is null .我无法访问组件 state,因为 setCount 是 function 内的私有变量,从render返回的examplenull

If I use a class component, then render returns a reference to the component and then I can call example.setState .如果我使用 class 组件,则render返回对该组件的引用,然后我可以调用example.setState But I prefer not to convert my component into a class if I can avoid it.但如果可以避免的话,我不希望将我的组件转换为 class。

The docs for render say : render文档

Render a React element into the DOM in the supplied container and return a reference to the component (or returns null for stateless components).在提供的容器中将 React 元素渲染到 DOM 中并返回对组件的引用(或返回 null 用于无状态组件)。

But my component does have a state (count), it just doesn't recognize it.但是我的组件确实有一个 state (计数),它只是无法识别它。 If it's not possible to use the return value from render , is there another way to "get" the component and then use setCount (or some other way to set the state)?如果无法使用render的返回值,是否有另一种方法可以“获取”组件然后使用 setCount (或其他设置状态的方法)?

Or do I just have to use a class component for this?还是我只需要为此使用 class 组件?

Thanks.谢谢。

There is no way to access the state from outside the component.无法从组件外部访问 state。 It's like trying to access a locally scoped variable from outside a function.这就像试图从 function 外部访问一个局部范围的变量。

Using a class component wouldn't help either since you wouldn't be able to get hold of the instance of the class created inside the React app.使用 class 组件也无济于事,因为您无法获取在 React 应用程序中创建的 class 实例。


If you want to trigger a state change from outside the application, then the application needs to provide an event handler.如果要从应用程序外部触发 state 更改,则应用程序需要提供事件处理程序。

For (a really quick and dirty) example:对于(一个非常快速和肮脏的)示例:

const outside = {
    value: 2,
    callbacks: [],
    addCallback: function (callback) { this.callbacks.push(callback); },
    setValue: function (value) { 
        this.value = value; 
        this.callbacks.forEach(
            callback => callback(this.value)
        );
    }
};

function Component = () => {
    const [val, setVal] = useState(outside.value);
    useEffect(() => {
        outside.addCallback((value) => setVal(value));
    }, []);
    return <p>{val}</p>
}

It is possible.有可能的。 You could pass your setCount function as a parameter to use it in your JS outside of React - but I would not really recommend this.您可以将setCount function 作为参数传递给 React 之外的 JS 中使用它 - 但我不会真的推荐这个。

I would recommend that you keep your business logic and React logic separate.我建议您将业务逻辑和 React 逻辑分开。

The only things that need to be aware of state and will be using it are React components themselves.唯一需要注意 state 并将使用它的是 React 组件本身。 I would structure your code in a way that it is not coupled to React, and does not have to use or depend on React state in any way.我会以不与 React 耦合的方式构建您的代码,并且不必以任何方式使用或依赖 React state。

This is easier said than done at the beginning.这在开始时说起来容易做起来难。 If you need help with it, maybe provide a use case that you are trying to solve in this way, and a better answer might be provided.如果您需要帮助,也许可以提供一个您试图以这种方式解决的用例,并且可能会提供更好的答案。

It can be done by extending Example so it will pass a reference to the setCount function back to the parent code, see below.这可以通过扩展Example来完成,因此它将对setCount function 的引用传递回父代码,见下文。 (This might be the same as what Oli mentioned, if so then I had the same idea and made a working implementation before answering) (这可能与 Oli 提到的相同,如果是这样,那么我有相同的想法并在回答之前做了一个工作实现)

 const { useState } = React; // functionFromComponent will store the function from Example. let functionFromComponent = undefined; const setter = (someFn) => functionFromComponent = someFn; const Example = ({ setFunction }) => { // take `setFunction` from props const [count, setCount] = useState(0); setFunction(setCount); // pass setCount to the parent code return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } ReactDOM.render( <Example setFunction={setter} />, document.getElementById('example-wrapper') ); function buttonClicked() { if (functionFromComponent) { functionFromComponent(777); } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script> <div id="example-wrapper"></div> <button id="regularButton" onclick="buttonClicked()">Regular button</button>

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

相关问题 重写香草JavaScript中的React功能组件 - Rewrite react functional component in vanilla javascript 如何从 React 功能组件返回数据 - How to return data from a React Functional Component 保存从 promise 返回的数据并将其传递给反应中的另一个组件 - Save and pass data returned from a promise to functional another component in react React:为什么我不能将数据从一个功能组件传递到另一个功能组件? - React: Why can't I pass data from one functional component to another functional component? 如何在 React 中将数组作为结果从一个功能组件传递到另一个功能组件 - How to pass array as result from one functional component to another in React 如何通过 React Router Link 将值从功能组件传递到另一个功能组件? - How can I pass values from a functional component through a React Router Link to another functional component? 在 React 中将功能组件从子组件传递给父组件 - Pass functional component from child to parent in React 如何在反应中将类组件作为功能道具传递? - How to pass class component as a functional prop in react? 如何在React的功能组件中将参数传递给功能 - How to pass arguments to function in functional component in React 如何通过钩子 function 反应功能组件 - How to pass hook function to react functional component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM