외부에서 React 컴포넌트 메소드 호출
React Element의 인스턴스에서 React 컴포넌트에 의해 노출 된 메서드를 호출하고 싶습니다.
예를 들어,이 jsfiddle . 참조 에서 alertMessage
메서드 를 호출하고 싶습니다 HelloElement
.
추가 래퍼를 작성하지 않고도이를 달성 할 수있는 방법이 있습니까?
편집 (JSFiddle에서 복사 한 코드)
<div id="container"></div>
<button onclick="onButtonClick()">Click me!</button>
var onButtonClick = function () {
//call alertMessage method from the reference of a React Element! Something like HelloElement.alertMessage()
console.log("clicked!");
}
var Hello = React.createClass({displayName: 'Hello',
alertMessage: function() {
alert(this.props.name);
},
render: function() {
return React.createElement("div", null, "Hello ", this.props.name);
}
});
var HelloElement = React.createElement(Hello, {name: "World"});
React.render(
HelloElement,
document.getElementById('container')
);
내부 함수에 액세스하는 방법에는 두 가지가 있습니다. 하나는 인스턴스 수준, 원하는대로 다른 정적 수준입니다.
예
에서 반환 할 때 함수를 호출해야합니다 React.render
. 아래를 참조하십시오.
공전
ReactJS Statics를 살펴보십시오 . 단, 정적 기능을하지 액세스 인스턴스 레벨 데이터는 그렇게 할 수 this
있을 것입니다 undefined
.
var onButtonClick = function () {
//call alertMessage method from the reference of a React Element!
HelloRendered.alertMessage();
//call static alertMessage method from the reference of a React Class!
Hello.alertMessage();
console.log("clicked!");
}
var Hello = React.createClass({
displayName: 'Hello',
statics: {
alertMessage: function () {
alert('static message');
}
},
alertMessage: function () {
alert(this.props.name);
},
render: function () {
return React.createElement("div", null, "Hello ", this.props.name);
}
});
var HelloElement = React.createElement(Hello, {
name: "World"
});
var HelloRendered = React.render(HelloElement, document.getElementById('container'));
그런 다음 HelloRendered.alertMessage()
.
당신은 좋아할 수 있습니다
import React from 'react';
class Header extends React.Component{
constructor(){
super();
window.helloComponent = this;
}
alertMessage(){
console.log("Called from outside");
}
render(){
return (
<AppBar style={{background:'#000'}}>
Hello
</AppBar>
)
}
}
export default Header;
이제이 컴포넌트 외부에서 아래와 같이 호출 할 수 있습니다.
window.helloComponent.alertMessage();
다음과 같이했습니다.
class Cow extends React.Component {
constructor (props) {
super(props);
this.state = {text: 'hello'};
}
componentDidMount () {
if (this.props.onMounted) {
this.props.onMounted({
say: text => this.say(text)
});
}
}
render () {
return (
<pre>
___________________
< {this.state.text} >
-------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
</pre>
);
}
say (text) {
this.setState({text: text});
}
}
그리고 다른 곳 :
class Pasture extends React.Component {
render () {
return (
<div>
<Cow onMounted={callbacks => this.cowMounted(callbacks)} />
<button onClick={() => this.changeCow()} />
</div>
);
}
cowMounted (callbacks) {
this.cowCallbacks = callbacks;
}
changeCow () {
this.cowCallbacks.say('moo');
}
}
나는이 정확한 코드를 테스트하지 않았지만 이것은 내가 프로젝트에서 한 일을 따라 잘 작동합니다. :). 물론 이것은 나쁜 예입니다. props를 사용해야하지만 제 경우에는 하위 구성 요소가 해당 구성 요소 내부에 유지하려는 API 호출을 수행했습니다. 그러한 경우 이것은 좋은 해결책입니다.
와 render
방법은 잠재적으로 반환 값을 비하, 권장되는 방법은 루트 요소에 콜백 심판을 첨부 할 지금이다. 이렇게 :
ReactDOM.render( <Hello name="World" ref={(element) => {window.helloComponent = element}}/>, document.getElementById('container'));
그런 다음 window.helloComponent를 사용하여 액세스 할 수 있으며 모든 메서드는 window.helloComponent.METHOD를 사용하여 액세스 할 수 있습니다.
다음은 전체 예입니다.
var onButtonClick = function() {
window.helloComponent.alertMessage();
}
class Hello extends React.Component {
alertMessage() {
alert(this.props.name);
}
render() {
return React.createElement("div", null, "Hello ", this.props.name);
}
};
ReactDOM.render( <Hello name="World" ref={(element) => {window.helloComponent = element}}/>, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
<button onclick="onButtonClick()">Click me!</button>
ES6에있는 경우 예제의 메서드에 "static"키워드를 사용하면 다음과 같습니다. static alertMessage: function() { ...
},
희망은 누구든지 도울 수 있습니다 :)
class AppProvider extends Component {
constructor() {
super();
window.alertMessage = this.alertMessage.bind(this);
}
alertMessage() {
console.log('Hello World');
}
}
을 사용하여 창에서이 메서드를 호출 할 수 있습니다 window.alertMessage()
.
onClick
함수 ( onClick
React의 자체 구현 onClick
) 를 사용하여 div에 핸들러를 추가하고 { }
중괄호로 속성에 액세스 할 수 있으며 경고 메시지가 나타납니다.
컴포넌트 클래스에서 호출 할 수있는 정적 메소드를 정의하려면 정적을 사용해야합니다. 이기는 하지만:
"Methods defined within this block are static, meaning that you can run them before any component instances are created, and the methods do not have access to the props or state of your components. If you want to check the value of props in a static method, have the caller pass in the props as an argument to the static method." (source)
Some example code:
const Hello = React.createClass({
/*
The statics object allows you to define static methods that can be called on the component class. For example:
*/
statics: {
customMethod: function(foo) {
return foo === 'bar';
}
},
alertMessage: function() {
alert(this.props.name);
},
render: function () {
return (
<div onClick={this.alertMessage}>
Hello {this.props.name}
</div>
);
}
});
React.render(<Hello name={'aworld'} />, document.body);
Hope this helps you a bit, because i don't know if I understood your question correctly, so correct me if i interpreted it wrong:)
It appears statics are deprecated, and the other methods of exposing some functions with render
seem convoluted. Meanwhile, this Stack Overflow answer about debugging React, while seeming hack-y, did the job for me.
method 1 using ChildRef
:
public childRef: any = React.createRef<Hello>();
public onButtonClick= () => {
console.log(this.childRef.current); // this will have your child reference
}
<Hello ref = { this.childRef }/>
<button onclick="onButtonClick()">Click me!</button>
Method 2: using window register
public onButtonClick= () => {
console.log(window.yourRef); // this will have your child reference
}
<Hello ref = { (ref) => {window.yourRef = ref} }/>`
<button onclick="onButtonClick()">Click me!</button>
I have two answers for this question:
1- use your function as a static method:
statics: {
alertMessage: function () {
console.log('Method One');
}
},
But this method has a big problem, because in static methods you do not have access to this
and in a case that you want to use this
this method is not working so in such cases use method 2.
2- First in your class
:
constructor(props){
super(props);
window.alertMessage = this.alertMessage.bind(this);
}
alertMessage () {
console.log('Method Two');
}
then in every component you can use below command:
참고URL : https://stackoverflow.com/questions/31612598/call-a-react-component-method-from-outside
'Nice programing' 카테고리의 다른 글
각 루프에 대한 C #은 어떤 순서로 목록을 반복합니까? (0) | 2020.10.19 |
---|---|
Makefile에서 : =와 =의 차이점은 무엇입니까? (0) | 2020.10.19 |
WPF 애플리케이션을 다시 시작하려면 어떻게해야합니까? (0) | 2020.10.18 |
계수 나누기 (%)가 정수에서만 작동하는 이유는 무엇입니까? (0) | 2020.10.18 |
팬더 데이터 프레임 예쁜 인쇄 (0) | 2020.10.18 |