从另一个React组件调用函数

时间:2017-05-21 20:58:08

标签: reactjs

我的第一个组成部分如下:

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数组的随机元素。

1 个答案:

答案 0 :(得分:5)

您可以通过多种方式实现这一目标:

您可以通过创建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))];
}
相关问题