2017-05-21 2 views
1

내 첫 번째 구성 요소는 다음과 같다 구성 요소를 반응한다. 지금까지 본 모든 대답은 부모와 자녀 관계에 대해 이야기하지만,이 경우 두 구성 요소는 관계가 없습니다. 나는이 같은 생각하지만, 일하지 않는 : 나는 인생에서 인쇄 hellos 배열의 임의 요소를 좀하고 싶습니다통화 기능은

import { Welcome } from './Welcome' 

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

합니다.

+1

올바른 디자인 패턴처럼 보이지 않습니다. – Li357

+0

메서드 호출과 함께 줄을 깜박했습니다. – ocram

+0

Life 구성 요소에서 어떤 일이 발생할 것으로 예상합니까? 환영합니다 구성 요소가 표시되어야합니까? 현재 코드는 그렇지 않기 때문입니다. – nem035

답변

2

당신이 얻을 수있는 여러 가지 방법이 있습니다

당신은의 sayHello 함수를 작성하고 명명 된 기능으로 간단하게 사용하여이 작업을 수행 할 수는. 이다하는 https://www.webpackbin.com/bins/-KkgrwrMGePG4ixI0EKd

또 다른 방법을 만든

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')); 

: 가져올 수있는

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

적 요소되는 경우 기능을 공유하고자 단순히 sayHello 함수를 정적으로 정의하십시오.

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

또는 구성 요소에 대한 참조를 사용하여 해당 구성 요소에 대한 메소드를 호출 할 수 있습니다. –