亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在react js中從一個組件到另一個組件獲取價值?

如何在react js中從一個組件到另一個組件獲取價值?

慕村225694 2021-08-13 16:23:42
我試圖在 props 的幫助下從其他組件中獲取價值,但它不起作用。這是我的邏輯main.js 向 child.js 組件發出請求,在 child.js 中我變老了,但它不起作用。class Main Connect extends Component {   constructor(props) {       this.age = this.props.age   }   render() {      <Child />      return(this.age)   }}class Child Connect extends Component {   render()      return(<Main age='21' />)}
查看完整描述

2 回答

?
慕尼黑8549860

TA貢獻1818條經驗 獲得超11個贊

您的兩個組件看起來都有問題,需要進行許多更正


你的代碼


    //don’t what is Connect here. A class followed its class name must be single word

     class Main Connect extends Component {

           constructor(props) {

               //you need to call super(props); here to get props from parent inside constructor 

               // set age to a state but what you are doing below isn’t right way

               this.age = this.props.age

            }


          render() {

              // this is totally wrong check my corrected code below to understand better

             <Child />

                 return(this.age)

              }


         }


        class Child Connect extends Component {


               render()

                  return(<Main age='21' />)


         }

檢查以下更新的代碼。這是從父到子的工作方式


   class Main extends Component{

       render() {

          return (<div><Child age='21' /></div>)

       }

    }


   class Child extends Component {

       constructor(props){

           super(props);

           this.state = {

               age: props.age

           }

       }

       render(){

           return(<div><h1>{this.state.age}</h1></div>)

       }

PS:- 你得到了其他人的反對票,因為句子不正確,而且你發布的內容不完整,有很多問題。


查看完整回答
反對 回復 2021-08-13
?
慕妹3146593

TA貢獻1820條經驗 獲得超9個贊

我不確定你的情況是什么。輸入元素的變化是向上傳遞 props 的典型情況。為此,通過屬性使用函數來處理更改(并將實際值傳遞回輸入):


主程序


import AgeInput from './AgeInput';


class Main extends Component {

  state = {

    age: ''

  }


  handleAgeInputChange = ({target}) => {

    const { value: age } = target;

    this.setState({ age })

  }


  render() {

    return <AgeInput onChange={this.handleAgeInputChange} value={this.state.age} />

  }

}

AgeInput.js(兒童)


const AgeInput = ({ onChange, value }) => (

  <input onChange={onChange} value={value} />

);


export default AgeInput;


查看完整回答
反對 回復 2021-08-13
  • 2 回答
  • 0 關注
  • 235 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號