0

嘿,我正在尝试使用在 jsx 中工作的这段代码

import React from 'react';
import styled from 'styled-components';

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

class ShoppingList extends React.Component {
  state = {
    smallList: [],
    sum: ''
  }

  componentDidMount() {
    this.setState({
      smallList: [''],
      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([''])
    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 default ShoppingList;

到tsx,如你所见,我不使用props,在组件中,只是给另一个组件一个prop,那怎么办?为了使 tsx 没有道具,当我为这样的类型声明接口时

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

然后在组件中说找不到this.state.smallList,这是为什么呢?

4

1 回答 1

0

添加此代码应该可以解决问题

class ShoppingList extends React.Component< Props, State> {....}

这里定义状态接口,并用相同的方式扩展你的类。

于 2018-12-25T16:12:09.060 回答