如何在React中定义,提供输入并使用变量?

时间:2019-05-02 18:39:49

标签: reactjs gatsby

我想定义一个变量,从输入中设置其值,然后在每个渲染周期的函数中调用该变量。应该怎么做?

export default ({priceAtInvestment, currentPrice}) => {
    <main>
        <h1>
            <span>If you had invested $</span>
            <input name="investmentAmount" type="number" value={investmentAmount}></input>
            <span>in</span>
            <select name="stockName">
                <option value="NFLX">Netflix</option>
                <option value="AMZN">Amazon</option>
            </select>
            <span>on</span>
            <input name="investmentDate" type="date" value="1995-06-13" ></input>
        </h1>
        {calculateStockValue(priceAtInvestment, currentPrice, investmentAmount)}
    </main>
}

1 个答案:

答案 0 :(得分:0)

在Gatsby应用中使用最新版本的react即16.8.0或更高版本,您可以在功能组件中使用useState来存储输入值的状态

export default ({priceAtInvestment, currentPrice}) => {
  const [investmentAmount, setInvestmentAmount] = useState(0);
  return (
    <main>
        <h1>
            <span>If you had invested $</span>
                <input name="investmentAmount" type="number" value={investmentAmount} onClick={(e) => setInvestmentAmount(e.target.value)}></input>
            <span>in</span>
                <select name="stockName">
                    <option value="NFLX">Netflix</option>
                    <option value="AMZN">Amazon</option>
                </select>
            <span>on</span>
                <input name="investmentDate" type="date" value="1995-06-13" ></input>
        </h1>
        {calculateStockValue(priceAtInvestment, currentPrice, investmentAmount)}
    </main>
  )
}

否则,您将需要在类组件中转换应用

export default class Investment extends React.Component {
   state = {
      investmentAmount: 0
   }
   setInvestmentAmount = (e) => {
      this.setState({investmentAmount: e.target.value})
   }
   render() {
      const {priceAtInvestment, currentPrice} = this.props;
      const {investmentAmount} = this.state;
      return (
        <main>
            <h1>
                <span>If you had invested $</span>
                    <input name="investmentAmount" type="number" value={investmentAmount} onClick={this.setInvestmentAmount}></input>
                <span>in</span>
                    <select name="stockName">
                        <option value="NFLX">Netflix</option>
                        <option value="AMZN">Amazon</option>
                    </select>
                <span>on</span>
                    <input name="investmentDate" type="date" value="1995-06-13" ></input>
            </h1>
            {calculateStockValue(priceAtInvestment, currentPrice, investmentAmount)}
        </main>
      )
    }
}