嘿,我正在尝试采用可在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,如您所见,我在组件中不使用道具,只需将道具提供给另一个组件,那怎么办?
为了使tsx没有道具,当我声明类型的接口时
像这样
interface SLState {
smallList: string[];
sum: number
}
然后在表示无法找到this.state.smallList的组件中,为什么?
答案 0 :(得分:0)
添加此代码即可解决问题
class ShoppingList extends React.Component< Props, State> {....}
在此定义状态接口,并使用相同的类扩展您的类。