【问题标题】:React js conversion to typescript, adding data to const, interfaceReact js 转换为 typescript,添加数据到 const,interface
【发布时间】:2018-06-14 06:27:20
【问题描述】:

我已经开始研究 react typescript。我正在使用语义 ui 创建一个下拉组件。问题是语义 Ui 提供了更容易理解的 java 脚本格式的代码。我需要将以下代码转换为打字稿。我成功地完成了其中的一些操作,但是在向 memberOptions 添加新值时转换 handleAddition 时遇到问题。 下面是JS的代码。

我不确定是否可以在 typescript 中使用 setState。

const memberOptions = [
    {
        text: 'Bruce',
        value: 'bruce'
    },
    {
        text: 'Clark',
        value: 'clark'
    },
    {
        text: 'Diana',
        value: 'diana'
    },
    {
        text: 'Peter',
        value: 'peter'
    }
];

class DropdownExampleAllowAdditions extends Component {
  state = { memberOptions }

  handleAddition = (e, { value }) => {
    this.setState({
       memberOptions: [{ text: value, value }, 
         ...this.state.memberOptions],
    })
  }

  handleChange = (e, { value }) => this.setState({ currentValues: value })

  render() {
    const { currentValues } = this.state

    return (
      <Dropdown
        options={this.state.options}
        placeholder='Choose Languages'
        value={currentValues}
        onAddItem={this.handleAddition}
        onChange={this.handleChange}
      />`enter code here`
    )
  }
}

我需要将 handleAddition 转换为打字稿。是否有一些关于它们的规则?

【问题讨论】:

  • 你可以在 typescript 中完全使用上面的代码。唯一的变化是 import * as React from 'react';和类 DropdownExampleAllowAdditions 扩展 React.Component {
  • 我试过了,但它不起作用。我现在唯一遇到的问题是向 MemberDropdown 添加价值时。

标签: javascript reactjs typescript


【解决方案1】:
Here is the solution. The trick is how you manage the state.

const options = [
    {
        text: 'Bruce',
        value: 'bruce'
    },
    {
        text: 'Clark',
        value: 'clark'
    },
    {
        text: 'Diana',
        value: 'diana'
    },
    {
        text: 'Peter',
        value: 'peter'
    }
];

interface Props {
    options? : any
}

export default class DropdownExampleAllowAdditions extends React.PureComponent<Props> {
    constructor(props: Props) {
        super(props);
        this.state = {options:{}};
    }`enter code here`

  const handleAddition = (e: {}, {value}: {value:string}) => {                
                        this.setState({
                            options: [{ text: value, value }, ...this.state.options],
                          })
                    }

  const handleChange = (e: {}, { value }: { value: string }) =>
                        form.setFieldValue(fieldName, value);

  render() {
    const { options } = this.props;

    return (
      <Dropdown
        options={this.state.options}
        placeholder='Choose Languages'
        value={currentValues}
        onAddItem={handleAddition}
        onChange={handleChange}
      />`enter code here`
    )
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2021-04-01
    • 2018-02-22
    • 1970-01-01
    • 2014-08-27
    • 2017-05-28
    • 2021-12-30
    相关资源
    最近更新 更多