IT

ReactJS 호출 메소드

lottoking 2020. 7. 24. 07:25
반응형

ReactJS 호출 메소드


ReactJS에서 첫 걸음을 내딛고 부모와 자녀 사이의 의사 소통을 이해합니다. 양식을 작성하고 있으므로 스타일 필드의 구성 요소가 있습니다. 또한 필드를 포함하고 확인하는 부모 구성 요소가 있습니다. 예 :

var LoginField = React.createClass({
    render: function() {
        return (
            <MyField icon="user_icon" placeholder="Nickname" />
        );
    },
    check: function () {
        console.log ("aakmslkanslkc");
    }
})

var MyField = React.createClass({
    render: function() {
...
    },
    handleChange: function(event) {
//call parent!
    }
})

그것을 할 수있는 방법이 있습니까? 그리고 내 논리는 reactjs "world"에 능숙합니까? 시간 내 줘서 고마워.


이를 위해 사용하기 위해 속성으로 부모에서 하위로 속성으로 전달합니다.

예를 들면 다음과 같습니다.

var Parent = React.createClass({

    getInitialState: function() {
        return {
            value: 'foo'
        }
    },

    changeHandler: function(value) {
        this.setState({
            value: value
        });
    },

    render: function() {
        return (
            <div>
                <Child value={this.state.value} onChange={this.changeHandler} />
                <span>{this.state.value}</span>
            </div>
        );
    }
});

var Child = React.createClass({
    propTypes: {
        value:      React.PropTypes.string,
        onChange:   React.PropTypes.func
    },
    getDefaultProps: function() {
        return {
            value: ''
        };
    },
    changeHandler: function(e) {
        if (typeof this.props.onChange === 'function') {
            this.props.onChange(e.target.value);
        }
    },
    render: function() {
        return (
            <input type="text" value={this.props.value} onChange={this.changeHandler} />
        );
    }
});

위의 예에서 의 속성을 사용하여 Parent호출합니다 . 대가는 결합 표준에 제공되는 요소와에 값을 전달 의 많은 경우에 정의되어 있습니다.ChildvalueonChangeChildonChange<input />Parent

결과적으로 ParentchangeHandler메소드가 <input />필드 의 값인 첫 번째 인수와 함께 호출 Child됩니다. 결과는 Parent의 상태를 해당 값으로 업데이트 할 수 있으므로 입력 필드에 입력 <span />때 부모 요소가 새 값으로 업데이트 Child됩니다.


모든 상위 메소드를 사용할 수 있습니다. 이를 위해 간단한 값처럼 부모에서 자녀에게이 방법을 보내야합니다. 그리고 한 번에 부모로부터 많은 방법을 사용할 수 있습니다. 예를 들면 다음과 같습니다.

var Parent = React.createClass({
    someMethod: function(value) {
        console.log("value from child", value)
    },
    someMethod2: function(value) {
        console.log("second method used", value)
    },
    render: function() {
      return (<Child someMethod={this.someMethod} someMethod2={this.someMethod2} />);
    }
});

그리고 이것을 다음과 같이 Child에게 사용하십시오 (임의의 작업이나 모든 메소드에).

var Child = React.createClass({
    getInitialState: function() {
      return {
        value: 'bar'
      }
    },
    render: function() {
      return (<input type="text" value={this.state.value} onClick={this.props.someMethod} onChange={this.props.someMethod2} />);
    }
});


반응 16 이상 및 ES6으로 2019 업데이트

관리자가 게시하는 것은 React.createClass반응 버전 16에서 더 이상 사용하지 않는 새로운 Javascript ES6은 더 많은 이점을 제공합니다.

부모의

import React, {Component} from 'react';
import Child from './Child';

export default class Parent extends Component {

    es6Function = (value) => {
        console.log(value)
    }

    simplifiedFunction (value) {
        console.log(value)
    }

    render () {
        return (
            <div>
                <Child
                    es6Function = {this.es6Function}
                    simplifiedFunction = {this.simplifiedFunction} 
                />
            </div>
        )
    }

}

아이

import React, {Component} from 'react';

export default class Child extends Component {

    render () {
        return (
            <div>
                <h1 onClick= { () =>
                        this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
                    }
                > Something</h1>
            </div>
        )
    }
}

SE6 상수로 단순화 된 상태 비 저장 자식

import React from 'react';

const Child = () => {
    return (
        <div>
            <h1 onClick= { () =>
                this.props.es6Function(<SomethingThatYouWantToPassIn>)
            }
            > Something</h1>
        </div>
    )

}
export default Child;

Parent컴포넌트 에서 컴포넌트로 메소드를 prop전달하십시오 Child. 즉 :

export default class Parent extends Component {
  state = {
    word: ''
  }

  handleCall = () => {
    this.setState({ word: 'bar' })
  }

  render() {
    const { word } = this.state
    return <Child handler={this.handleCall} word={word} />
  }
}

const Child = ({ handler, word }) => (
<span onClick={handler}>Foo{word}</span>
)

반응 16+

하위 구성 요소

import React from 'react'

class ChildComponent extends React.Component
{
    constructor(props){
        super(props);       
    }

    render()
    {
        return <div>
            <button onClick={()=>this.props.greetChild('child')}>Call parent Component</button>
        </div>
    }
}

export default ChildComponent;

부모 구성 요소

import React from "react";
import ChildComponent from "./childComponent";

class MasterComponent extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state={
            master:'master',
            message:''
        }
        this.greetHandler=this.greetHandler.bind(this);
    }

    greetHandler(childName){
        if(typeof(childName)=='object')
        {
            this.setState({            
                message:`this is ${this.state.master}`
            });
        }
        else
        {
            this.setState({            
                message:`this is ${childName}`
            });
        }

    }

    render()
    {
        return <div>
           <p> {this.state.message}</p>
            <button onClick={this.greetHandler}>Click Me</button>
            <ChildComponent greetChild={this.greetHandler}></ChildComponent>
        </div>
    }
}
export default  MasterComponent;

참고 URL : https://stackoverflow.com/questions/26176519/reactjs-call-parent-method

반응형

'IT' 카테고리의 다른 글

여러 줄 문자에 줄임표 적용  (0) 2020.07.24
대체에서 데이터 유형을 변경하는 방법  (0) 2020.07.24
키워드와 키워드의 차이점  (0) 2020.07.24
패키지 목록을위한 Spring Boot yaml 구성  (0) 2020.07.24
R 발광  (0) 2020.07.24