1、项目安装运行
create-react-app 你的项目名 --typescript  
npm start
2、项目首页

首页

import React from 'react';
import logo from './logo.svg';
import './App.css';
import Arrowlist from './home';

const App: React.FC = () => {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

3、使用ts创建一个页面
import React from 'react';
interface Props {
    datas: Array<string>
}
interface State {
    show: boolean;
    select: string
}
class Arrowlist extends React.Component<Props, State> {
    static defaultProps: Props = {
        datas: ["1", "2", "3", "4"]
      } as any;
    constructor(props: any){
        super(props);
        this.state = {show: false, select:""};
    }
    render() {
        return <div className="infor-popverdd">
            <div onClick={() => {
                this.setState({ show: !this.state.show });
            }}>
                {this.props.children}
            </div>
            <div style={{ height: `${this.props.datas.length * 34}px`, display: `${this.state.show ? "block" : "none"}` }}>
                <i></i>
                {this.props.datas.map((item) => {
                    return <span key={item} className={+this.state.select === +item ? "active" : ""} onClick={() => {
                        this.setState({ select: item, show: !this.state.show });
                    }}>{item}</span>
                })}
            </div>
        </div>
    }
}
export default Arrowlist;

修改首页代码引入组件

import React from 'react';
import logo from './logo.svg';
import './App.css';
import Arrowlist from './home';

const App: React.FC = () => {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
        <Arrowlist datas={["1", "2", "3", "4"]}>下拉弹框</Arrowlist>
      </header>
    </div>
  );
}

export default App;

4、其他

设置Props的两种方法

static defaultProps: Props = {
    datas: ["1", "2", "3", "4"]
} as any;

Arrowlist.defaultProps = {
    title: "下拉弹框",
    datas: [1, 2, 3],
}
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐