【问题标题】:How to pass the input value from child to parent in react typescript如何在反应打字稿中将输入值从孩子传递给父母
【发布时间】:2019-12-23 19:50:38
【问题描述】:

父组件:

import React from "react";
import InputRow from "./InputRow";

const Bid: React.FunctionComponent = () => {
const inpVal = (d:string) => {
}

return (
<div style={{ display: "none" }} className="bid-container animated zoomIn" id="bid-modal">
  <p>Mortage</p>
  <div className="bid-row-container">
    <p>Enter your bid</p>
    <div className="bid-row">
      <InputRow bid="Bid" inpVal={(inpVal: string)=>{console.log(inpVal)}} />
    </div>
  </div>
</div>
);
};

export default Bid;

子组件:

import React from "react";

interface Props{
bid: string,
inpVal: (inpVal:string) => void;
}

const InputRow: React.FunctionComponent<Props> = (bid, inpVal) => {


 return (
<div className="input-row">
  <div>
    <input type="text"  onChange={(e) => { inpVal(e.target.value) }} />
    <p>Rate</p>
  </div>

  <button className="bid-btn">{bid.bid}</button>
</div>
);
};

 export default InputRow;

我正在尝试将输入值从子组件传递到父组件,但它会抛出错误。

TypeError: inpVal 不是函数。

【问题讨论】:

    标签: javascript reactjs react-typescript


    【解决方案1】:

    使用 props 函数传值

    How to pass data from child component to its parent in ReactJS?

    家长:

    <div className="col-sm-9" >
         <SelectLanguage onSelectLanguage={this.handleLanguage}/> 
    </div>
    

    孩子:

    handleLangChange = () => {
        var lang = this.dropdown.value;
        this.props.onSelectLanguage(lang);            
    }
    

    【讨论】:

      【解决方案2】:

      您需要将参数包装在{} 中,这将从props 对象中提取bidinpVal

      const InputRow: React.FunctionComponent<Props> = ({ bid, inpVal }) => {...}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-06
        • 2020-10-31
        • 2020-07-22
        • 2022-09-26
        • 2018-03-29
        • 2020-09-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多