【问题标题】:Modify the state with other component for the input in React使用其他组件修改 React 中输入的状态
【发布时间】:2021-08-03 06:21:26
【问题描述】:

我执行了一个可以修改产品价格的项目(从伪造的 API 中恢复),然后单击按钮通过计算 20% 的增值税来执行更新。我遇到了一个问题,我想要一个价格状态,在这种状态下它是我输入的值,即 {listProduct.price},但它不起作用。

如果你有解决方案,我很感兴趣,提前谢谢你。 (对不起,我是 React 的新手,我对所有这些概念还是有点麻烦)

import React, { Component } from 'react'
import '../css/ProductsDetails.css'
import {AiOutlineArrowLeft} from "react-icons/ai";
import {Link} from 'react-router-dom'


export default class ProductsDetails extends Component {
    state = {
        id: this.props.match.params.id,
        price: 
    }
    updatePrice = (e) => {
        console.log(e);
        this.setState({
            price: e.target.value
        })
    }

    render() {
        const {location: {state: {listProduct}}} = this.props;
        return (
            <div className="products__details">
                <Link to="/"><AiOutlineArrowLeft className="nav__arrow" /></Link>
                <h1 className="details__title">{listProduct.title}</h1>
                <div className="details__align--desk">
                    <div className="details__img">
                    <img className="product__img" src={listProduct.image} alt="Affichage du produit"/>
                    </div>
                    <div className="products__align--desk">
                        <h2 className="product__title">Description</h2>
                        <p className="product__description">{listProduct.description}</p>
                        <h2 className="product__title">Price</h2>
                        <form className="form__price">
                            <input className="input__price" type="text" value={listProduct.price} onChange={this.updatePrice} />
                            <p>Price (including VAT): {Math.round((listProduct.price + listProduct.price * 0.2)*100) /100} €</p>
                            <br/>
                            <input className="btn__update" type="submit" value="Update product" />
                        </form>
                    </div>
                    <div className="category__align--desk">
                        <h2 className="product__title">Category</h2>
                        <p className="product__category">{listProduct.category}</p>
                    </div>
                </div>
            </div>
        )
    } 
}

export default class Products extends Component {
    constructor(props) {
      super(props);
      this.state = {productsData: []};
    }
      componentDidMount = () => {
        axios.get('https://fakestoreapi.com/products?limit=7')
        .then(res => {
          console.log(res.data)
          this.setState ({
            productsData: res.data
          })
        })
      }
    render() {
        const listsProducts = this.state.productsData.map(listProduct => {
            return <tbody className="products__body">
                    <tr>
                        <td> <Link to={{pathname: "/products-details/" + listProduct.id,state: {listProduct}}}>{listProduct.title}</Link></td>
                        <td className="products__category">{listProduct.category}</td>
                        <td>{listProduct.price}</td>
                        <td>{Math.round((listProduct.price + listProduct.price * 0.2)*100) /100}</td>
                    </tr> 
              </tbody>
          })
        return (
            <main className="products">
                <h1 className="products__title">Products management</h1>
                <table cellSpacing="0">
                <thead className="products__head">
                    <tr>
                    <th className="table--title">Product name</th>
                    <th className="table--title">Category</th>
                    <th className="table--title">Price</th>
                    <th className="table--title">Price (including VAT)</th>
                    </tr>
                </thead>
                  {listsProducts}
                </table>
            </main>
        )
    }
}

【问题讨论】:

    标签: reactjs components state


    【解决方案1】:

    在反应组件内部:

    1 - 您声明组件的初始状态,在这种情况下,即在用户写东西之前产品的价格。现在,我们将其设置为 0:

    state = {
      id: this.props.match.params.id, 
      price: this.props.listProduct.price ? this.props.listProduct.price : 0
    }
    

    2 - 然后,在render 方法中,我们从this.state 访问price

    3 - 最后,我们修改 input 元素,使其获得价格的值。

    <input className="input__price" type="text" value={price} onChange={this.updatePrice} />
    

    组件的其余部分运行良好。

    这是结果:

    import React, { Component } from 'react'
    import '../css/ProductsDetails.css'
    import {AiOutlineArrowLeft} from "react-icons/ai";
    import {Link} from 'react-router-dom'
    
    
    export default class ProductsDetails extends Component {
        state = {
            id: this.props.match.params.id,
            price: '0'
        }
        updatePrice = (e) => {
            console.log(e);
            this.setState({
                price: e.target.value
            })
        }
    
        render() {
            const {price} = this.state
            return (
                <div className="products__details">
                    <Link to="/"><AiOutlineArrowLeft className="nav__arrow" /></Link>
                    <h1 className="details__title">{listProduct.title}</h1>
                    <div className="details__align--desk">
                        <div className="details__img">
                        <img className="product__img" src={listProduct.image} alt="Affichage du produit"/>
                        </div>
                        <div className="products__align--desk">
                            <h2 className="product__title">Description</h2>
                            <p className="product__description">{listProduct.description}</p>
                            <h2 className="product__title">Price</h2>
                            <form className="form__price">
                                <input className="input__price" type="text" value={price} onChange={this.updatePrice} />
                                <p>Price (including VAT): {Math.round((listProduct.price + listProduct.price * 0.2)*100) /100} €</p>
                                <br/>
                                <input className="btn__update" type="submit" value="Update product" />
                            </form>
                        </div>
                        <div className="category__align--desk">
                            <h2 className="product__title">Category</h2>
                            <p className="product__category">{listProduct.category}</p>
                        </div>
                    </div>
                </div>
            )
        } 
    }
    

    【讨论】:

    • 谢谢你的回答,除了我不想在我的输入中显示 0 作为起始价格,而是我从我的 API 获得的价格然后更改它
    • state = {id: this.props.match.params.id, price: this.props.listProduct.price}
    • 谢谢@Bafsky,我也尝试过这样做,但它给了我一个错误:“TypeError: Cannot read property 'price' of undefined”
    • state = {id: this.props.match.params.id, price: this.props.listProduct ? this.props.listProduct.price : 0}
    • @Bafsky 非常感谢,我可以修改价格,但是您不知道如何显示我的 API 价格而不是 0,以便我稍后修改?
    【解决方案2】:

    从状态中0(不是引号)的价格开始,然后...

    const price = this.state.price || (this.props.listProduct ? this.props.listProduct.price : 0)
    
    <input className="input__price" type="text" value={price} onChange{this.updatePrice} />
    

    因此,如果状态值已更新,则将使用该值,否则将检查道具中的价格是否可用并使用该值,否则将显示为零。

    【讨论】:

    • 谢谢,但是当我把它放在输入中时:&lt;input className = "input__price" type = "text" value = {listProduct.price} onChange = {this.updatePrice} /&gt; 这让我的起价很好,即 105.95 欧元,但是当我输入时:const price = this.state.price || (this.props.listProduct? this.props.listProduct.price: 0) &lt;input className = "input__price" type = "text" value = {price} onChange {this.updatePrice} /&gt; 它只给我 0 而不是 105.95我想要一开始
    • 你确定你有0 没有引号?你也可以只使用null
    • 是的,在价格状态0 没有引号
    • 然后将其更改为您从...得到listProduct的任何地方...所以const price = this.state.price || (listProduct? listProduct.price: 0)
    • 在哪里更改?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    相关资源
    最近更新 更多