react hook入门

useState的使用

 

 代码

const Search = (props: any) => {
  // useState() 采用一个初始 state 作为参数,也可以像这样使用一个空字符串。
  // 使用 state 进行交互,别忘了 import React:
  // 同时它会返回包含两个值的数组,第一个值 searchTerm 表示当前 state;第二个值 setSearchTerm 是 state 的更新函数。
  const [searchTerm, setSearchTerm] = React.useState("");
  const handleChange = (e: any) => {
    const text = e.target.value
    setSearchTerm(text);
  }
  return (
    <>

      <input type="text" onChange={handleChange} />
      <p>
        {searchTerm}
      </p>

    </>
  );
}

 

下游的组件要使用 state,可以将其作为 props 传递;如果下游组件要更新 state,可以向下传递一个回调处理函数。

function App() {
  const [searchTerm, setSearchTerm] = React.useState("");
  const list = [
    {
      title: "1",
      context: "内容1"
    },
    {
      title: "2",
      context: "内容2"
    },
    {
      title: "12",
      context: "内容12"
    }
  ]
  const listData = list.filter(item => {
   return item.title.toLowerCase().includes(searchTerm.toLowerCase())
  })

  const handleSearch = (text: string) => {
    setSearchTerm(text);
  }
  return (
    <div className="App">
      <header className="App-header">

         <Search onSearch={handleSearch} text={searchTerm}></Search>
        <ul>
          {
            listData.map((item) => {
              return <li>{item.title}/<b>{item.context}</b></li>
            }
            )
          }

        </ul>
      </header>
    </div>
  );
}

const Search = (props: any) => {
  const handleChange = (e: any) => {
    const text = e.target.value
    props.onSearch(text)//调上游传递的方法
  }
  return (
    <>

      <input type="text" onChange={handleChange} />
      <p>
        {props.text}
      </p>

    </>
  );
}

 

posted @ 2022-09-06 15:25  明媚下雨天  阅读(23)  评论(0编辑  收藏  举报