javascript - 如何在 TSX 中将值从子组件传递给父组件?

标签 javascript reactjs typescript react-props react-tsx

父组件有这个

 value={this.onUpdate(index)}

onUpdate 会处理值和索引

在子组件中我有一个输入字段

onChange={this.handleText(index)}

这会调用一个想要将 Prop 发回的方法

this.props.value(sum);

我认为我需要为值(value)做界面,但是怎么做?

编辑: 家长:

import * as React from "react";
import styled from 'styled-components';
import ShoppingList from './ShoppingList';

const Container = styled.div`
  position:absolute;
  left:0;
  bottom:0;
  right:0;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
`;

interface Item {
  id: number;
  value: number;
}

interface TPState {
  shoppingLists2: object[];
  shoplistsums: Item[];
  sum: number;
}

class TotalPrice extends React.Component<{}, TPState> {
  constructor(props: {}) {
    super(props);
    this.state = {
      shoppingLists2: [ShoppingList],
      sum: 0,
      shoplistsums: []
    }
  }

  AddShoppingList = () => {
    let shoppingLists2 = this.state.shoppingLists2.concat(ShoppingList);
    console.log(shoppingLists2)
    this.setState({
      shoppingLists2,
    })
  }

  onUpdate = index => (value) => {
    console.log('index, value', index, value)
    let item: Item = {
      id: index,
      value: value
    }
    let shoplistsums = [...this.state.shoplistsums];
    var indexOfItem = shoplistsums.map(e => e.id).indexOf(item.id);
    if (indexOfItem === -1) {
      shoplistsums.push(item);
    }
    else {
      shoplistsums[indexOfItem] = item;
    }
    let sum = shoplistsums.map(this.amount).reduce(this.sum);
    this.setState({
      shoplistsums,
      sum
    })
  }

  amount(item) {
    return item.value;
  }

  sum(prev, next) {
    return prev + next;
  }

  render() {
    return (
      <div>
        {this.state.shoppingLists2.map((ShoppingList, index) => (
          <ShoppingList
            key={index}
            value={this.onUpdate(index)}
          />
        ))}
        <Container>
          <label>Total:</label>
          <label>{this.state.sum + ' €'}</label>
          <button onClick={this.AddShoppingList}>Add Receipt</button>
        </Container>
      </div>
    );
  }
}

export default TotalPrice;

child

import * as React from "react";
import styled from 'styled-components';

const Container = styled.div`
  display: flex;
  flex-direction: row;
  justify-content: space-between;
`;

export interface SLProps {
}

interface SLState {
  smallList: number[];
  sum: number;
}

export default class ShoppingList extends React.Component<SLProps, SLState> {
  constructor(props: SLProps) {
    super(props);
    this.state = {
      smallList: [0],
      sum: 0
    }
  }

  handleText = i => e => {
    let smallList = [...this.state.smallList];
    let x = e.target.value;
    if (isNaN(parseFloat(x))) {
      smallList[i] = 0;
    }
    else {
      smallList[i] = parseFloat(x);
    }
    let sum = smallList.reduce(function(a, b) {
      return a + b;
    });
    this.props.value(sum);
    this.setState({
      smallList,
      sum
    })
  }

  addExpense = e => {
    e.preventDefault()
    let smallList = this.state.smallList.concat([0])
    this.setState({
      smallList
    })
  }

  render() {
    return (
      <div>
        <Container>
          <select>
            <option value="food">Food</option>
            <option value="houseware">Houseware</option>
            <option value="entertainment">Entertainment</option>
          </select>
          <button onClick={this.addExpense}>Add expense</button>
        </Container>
        {this.state.smallList.map((question, index) => (
          <Container key={index}>
            <input
              type="text"
            />
            <input
              type="number"
              step="0.01"
              onChange={this.handleText(index)}
              value={question === 0 ? '' : question}
            />
          </Container>
        ))}
        <Container>
          <label>Total:</label>
          <label>{this.state.sum + ' €'}</label>
        </Container>
      </div>
    )
  }
}

最佳答案

export interface SLProps {
  value: (value: number) => void
}

关于javascript - 如何在 TSX 中将值从子组件传递给父组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51045538/

相关文章:

javascript - A-Frame AR.js 标记模式不起作用

javascript - 有没有办法在基于区域设置格式化货币时获得一致的输出

javascript - Service Worker 缓存脚本尝试加载旧数据

javascript - Angular 和 ui 路由器 - 如何定义路由

javascript - 将 JS 对象转换为 JSON 字符串

reactjs - 初始化Materializecss Meteor时M未定义

javascript - 如何将数组分配给状态变量?

Angular2 NgFor 在表达式中绑定(bind)数组

javascript - typescript 与 Marionette.js

javascript - 我可以在对象的方法中使用对象的属性而不使用 `this`