从另一个React组件调用函数

12

我的第一个组件如下:

const hellos = ['Hola', 'Salut', 'Hallo', 'Ciao', 'Ahoj', 'Annyeong-haseyo', 'Aloha', 'Howdy', 'Ni Hao', 'Konnichiwa']

export class Welcome extends Component {

    constructor(props) {
        super(props);
        this.state = {
            errors: []
        };
    }

    sayHello = function() {
        return hellos[Math.floor((Math.random()*hellos.length))];
    }

    render() {
        return (
            <div className="Welcome">

            </div>
        );
    }
}

我希望能够从另一个组件中调用sayHello()。到目前为止,我看到的所有答案都涉及父子关系,但在这种情况下,这两个组件之间没有任何关系。 我想到了以下方法,但它并不能完成工作:

import { Welcome } from './Welcome'

export const Life = () => (
    <div className="Life">
      <p>{ Welcome.sayHello() }</p>
    </div>
)

我希望在Life中打印出hellos数组的一个随机元素。

Translated:

I hope to print a random element of the hellos array in Life.


1
这似乎不是正确的设计模式... - Andrew Li
那么你期望在"Life"组件中发生什么?它是否应该显示"Welcome"组件?因为你当前的代码不会显示它。 - nem035
它必须是父子关系。React基于props和states架构。如果你想在其他组件中使用sayHello,那么你必须将sayHello作为prop从这个组件传递到其他组件。 - EdG
我添加了我现在期望得到的内容。@nem035 - ocram
值得备份并考虑您的React组件应该用于什么。它们是呈现元素,旨在作为生成渲染输出的整体目的的一部分从父级接收prop值。它们不应像库类那样使用。相反,您可以将sayHello()放入可重用的命名函数中,例如user2340824建议的那样。这特别有意义,因为您的sayHello()函数根本不依赖于组件状态。 - Erik Hermansen
显示剩余2条评论
1个回答

11

有几种方法可以实现这个目标:

您可以通过创建sayHello函数并将其简单地用作命名函数来实现此目的。

hello.js

const hellos = ['Hola', 'Salut', 'Hallo', 'Ciao', 'Ahoj', 'Annyeong-haseyo', 'Aloha', 'Howdy', 'Ni Hao', 'Konnichiwa'];

const sayHello = function() {
    return hellos[Math.floor((Math.random()*hellos.length))];
};

export { sayHello };

然后您可以将其导入任何希望共享功能的组件中:

import { sayHello } from './hello';

class CompA extends React.Component {
    render() {
        return <span>{sayHello()}</span>;
    }
}

class CompB extends React.Component {
    render() {
        return <span>{sayHello()}</span>;
    }
}

render(<span>
        <CompA />
        <CompB />
    </span>, document.querySelector('#app'));

创建了一个https://www.webpackbin.com/bins/-KkgrwrMGePG4ixI0EKd

另一种方法是将您的sayHello函数定义为静态函数。

static sayHello() {
    return hellos[Math.floor((Math.random()*hellos.length))];
}

或者你可以使用一个组件的引用,并在其上调用一个方法。 - John Ruddell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接