programing

대응 - 하위 구성 요소가 값을 상위 양식에 다시 보낼 수 있습니까?

css3 2023. 3. 16. 21:44

대응 - 하위 구성 요소가 값을 상위 양식에 다시 보낼 수 있습니까?

InputField&Button양식을 작성하기 위해 양식에 들어가는 사용자 지정 구성 요소입니다.문제는 버튼을 클릭했을 때 폼에 데이터(사용자 이름 및 비밀번호)를 사용하여 에이잭스를 실행할 수 있도록 데이터를 폼으로 되돌리려면 어떻게 해야 합니다.

export default auth.authApi(
  class SignUpViaEmail extends Component{

    constructor(props){
      super(props);
      this.state = {
        email : "",
        password : ""
      };
      this.storeEmail = this.storeEmail.bind( this );
      this.storePassword = this.storePassword.bind( this );
    }

    storeEmail(e){
      this.setState({ email : e.target.value });
    }

    storePassword(e){
      this.setState({ password : e.target.value });
    }

    handleSignUp(){
      this.props.handleSignUp(this.state);
    }

    render(){
      return(
        <div className="pageContainer">

          <form action="" method="post">
            <InputField labelClass = "label"
                        labelText = "Username"
                        inputId = "signUp_username"
                        inputType = "email"
                        inputPlaceholder = "registered email"
                        inputClass = "input" />
            <Button btnClass = "btnClass"
                    btnLabel = "Submit"
                    onClickEvent = { handleSignUp } />
          </form>
        </div>
      );
    }

  }
);

아니면 권장하지 않고 폼 내에 커스텀 자 컴포넌트를 작성하지 않는 것이 좋습니까?

자 컴포넌트 =>InputField

import React,
       { Component } from "react";

export class InputField extends Component{

  constructor( props ){
    super( props );
    this.state = {
      value : ""
    };
    this.onUserInput = this.onUserInput.bind( this );
  }

  onUserInput( e ){
    this.setState({ value : e.target.value });
    this.props.storeInParentState({[ this.props.inputType ] : e.target.value });
  }

  render(){
    return  <div className = "">
              <label htmlFor = {this.props.inputId}
                     className = {this.props.labelClass}>
                {this.props.labelText}
              </label>
              <input id = {this.props.inputId}
                     type = {this.props.inputType}
                     onChange = {this.onUserInput} />
              <span className = {this.props.validationClass}>
                { this.props.validationNotice }
              </span>
            </div>;
  }
}

에러: 에러가 표시된다.e.target is undefinedE-mail 펑크.

React의 단방향 데이터 바인딩 모델은 명시적으로 허용되지 않는 한 하위 구성 요소가 값을 상위 구성 요소로 다시 전송할 수 없음을 의미합니다.리액트 방법은 콜백을 자 컴포넌트에 전달하는 것입니다(Facebook의 "양식" 가이드 참조).

class Parent extends Component {
  constructor() {
    this.state = {
      value: ''
    };
  }
  
  //...
  
  handleChangeValue = event => this.setState({value: event.target.value});
  
  //...
  
  render() {
    return (
      <Child
        value={this.state.value}
        onChangeValue={this.handleChangeValue}
      />
    );
  }
}

class Child extends Component {
  //...
  
  render() {
    return (
      <input
        type="text"
        value={this.props.value}
        onChange={this.props.onChangeValue}
      />
    );
  }
}

부모 컴포넌트는 상태를 처리하는 반면 자녀 컴포넌트는 표시만 처리합니다.Facebook의 「Lifting State Up」가이드는, 이 방법을 학습하기 위한 좋은 자원입니다.

이렇게 하면 모든 데이터가 상위 구성요소(상태) 내에 존재하며 하위 구성요소는 해당 데이터를 업데이트하는 방법(소품으로 전달되는 콜백)만 제공됩니다.이것으로 문제가 해결되었습니다.상위 컴포넌트는 데이터가 저장되어 있기 때문에 필요한 모든 데이터에 액세스할 수 있지만 하위 컴포넌트는 다음과 같은 개별 요소에 대한 데이터 바인딩을 담당합니다.<input>태그를 지정합니다.


부록

이 코멘트에 대한 답변:

자 컴포넌트 목록을 렌더링하면 어떨까요?리프팅 상태 상승 기법에서 이 단일 진실 소스를 사용하면 부모가 모든 자식 입력의 모든 상태를 제어할 수 있습니다. 맞죠?그러면 부모 컴포넌트에서 (목록으로 렌더링된) 자 컴포넌트의 각 값 입력에 어떻게 접근할 수 있을까요?

이 경우 목록의 각 요소에 대해 하위 구성 요소를 연결할 수 있습니다.예를 들어 다음과 같습니다.

class Parent extends Component {
  //...
  handleChangeListValue = index => event => {
    this.setState({
      list: this.state.list
        .map((element, i) => i === index ? event.target.value : element)
    });
  }
  //...
  render() {
    return this.state.list.map((element, i) => (
      <Child
        value={element}
        onChangeValue={this.handleChangeListValue(i)}
      />
    ));

추신. 면책사항: 위의 코드 예는 문제의 개념(Lifting State Up)을 설명하기 위한 것일 뿐이며, 답변 시점의 리액트 코드 상태를 반영합니다.불변 및 가변 어레이 업데이트, 정적 및 동적 생성 함수, 상태 저장 및 순수 컴포넌트, 클래스 기반 및 후크 기반 상태 저장 컴포넌트 등 코드에 대한 기타 질문은 모두 별개의 질문으로 하는 것이 좋습니다.

반응 클래스 성분

Parent.js

import React, { Component } from 'react';
import Child from './child'
class Parent extends Component {
  state = {
    value: ''
  }
  onChangeValueHandler = (val) => {
    this.setState({ value: val.target.value })
  }
  render() {
    const { value } = this.state;
    return (
      <div>
        <p> the value is : {value} </p>
        <Child value={value} onChangeValue={this.onChangeValueHandler} />
      </div>
    );
  }
}

export default Parent;

Child.js

  import React, { Component } from 'react';
  class Child extends Component {
  render() {
  const { value , onChangeValue } = this.props;
  return (
    <div>
      <input type="text"  value={value} onChange={onChangeValue}/> 
    </div>
  );
}
}
  export default Child;

리액트 훅

Parent.js

import { useState } from "react";
import Child from "./child";    
export default function Parent() {
const [value, changeValue] = useState("");
return (
  <div>
    <h1>{value}</h1>
    <Child inputValue={value} onInputValueChange={changeValue} />
  </div>
 );
}

Child.js

export default function Child(props) {
return (
   <div>
       <input
        type="text"
        value={props.inputValue}
        onChange={(e) => props.onInputValueChange(e.target.value)}/>
   </div>
 );
}

Parent.js

   import SearchBar from "./components/SearchBar";
    
    function App() {
      const handleSubmit = (term) => {
         //Log user input
        console.log(term);
      };
    
      return (
        <div>
          <SearchBar onPressingEnter={handleSubmit} />
        </div>
      );
    }

export default App;

Child.js

import { useState } from "react";

function SearchBar({ onPressingEnter }) {
  const [UserSearch, setname] = useState("[]");

  /* The handleChange() function to set a new state for input */
  const handleChange = (e) => {
    setname(e.target.value);
  };
  const onHandleSubmit = (event) => {
    //prevent form from making a http request
    event.preventDefault();
    onPressingEnter(UserSearch);
  };
  return (
    <div>
      <form onSubmit={onHandleSubmit}>
        <input
          type="search"
          id="mySearch"
          value={UserSearch}
          onChange={handleChange}
          name="q"
          placeholder="Search the site…"
          required
        />
      </form>
    </div>
  );
}
export default SearchBar;

입력 필드에 "참조 이름"을 추가하여 다음과 같은 함수를 호출할 수 있습니다.

<InputField 
   ref="userInput"
   labelClass = "label"
   labelText = "Username"
   inputId = "signUp_username"
   inputType = "email"
   inputPlaceholder = "registered email"
   inputClass = "input" />

따라서 참조를 사용하여 액세스할 수 있습니다.

this.refs.userInput.getUsernamePassword();

여기서 getUsernamePassword 함수는 InputField 컴포넌트 내에 있으며 반환 시 상태를 설정하고 소품을 호출할 수 있습니다.handleSignUp

언급URL : https://stackoverflow.com/questions/41619166/react-can-a-child-component-send-value-back-to-parent-form