sourcecode

ReactJS 콜 부모 메서드

copyscript 2023. 3. 10. 22:42
반응형

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!
    }
})

그것을 할 수 있는 방법이 있나요?그리고 리액트J의 "세계"에서 내 논리가 좋은가요?시간 내주셔서 감사합니다.

이를 위해 콜백을 속성으로 부모로부터 자녀에게 전달합니다.

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

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

위의 예에서는ParentChild의 성질을 가지고value그리고.onChange.그Child대신 을 구속하다onChange표준에 준거한 핸들러<input />이 값을 에 전달합니다.Parent의 콜백이 정의되어 있는 경우.

그 결과,ParentchangeHandlermethod는 첫 번째 인수로 호출됩니다.<input />의 필드Child그 결과, 그 결과,Parent상태를 이 값으로 갱신할 수 있기 때문에 부모 상태가<span />새 값을 입력할 때 업데이트하기 위한 요소Child의 입력 필드.

react 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>
    )
  }
}

ES6 정수로 상태 비저장 자식 단순화

import React from 'react';

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

}
export default 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에 사용합니다(모든 액션 또는 모든 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} />);
    }
});

기능 사용 || 스테이트리스 컴포넌트

상위 컴포넌트

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

 export default function Parent(){

     const handleParentFun = (value) =>{
       console.log("Call to Parent Component!",value);
     }

     return (
         <>
             This is Parent Component
             <ChildComponent 
                 handleParentFun = {(value) => {
                     console.log("your value -->",value);
                     handleParentFun(value);
                 }}
             />
         </>
     );
 }

자 컴포넌트

import React from "react";


export default function ChildComponent(props){
    return(
        <> 
           This is Child Component 
           <button onClick={props.handleParentFun("Your Value")}>
               Call to Parent Component Function
           </button>
        </>
    );
}

메서드 전달원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

반응형