親の値をpropsとして子コンポーネントに渡し、propsとして表示させるやり方について聞きたいです
以下の手順であっているのでしょうか?
・親で子に渡したい関数、stateなどを子コンポーネントタグの中に記入
<TextInput ={setText} handleInputCchange={handleInputCchange} />
↓
①子コンポーネントでpropsとして渡ってくる値を定義
interface Props {
text: string
handleInputCchange: React.ChangeEvent<HTMLInputElement>
}
↓
②Propsを使う
React.FC<Props> = (props)
↓
③propsとして表示させたいとこに記入
value={props.text}
onChange={props.handleInputChange}
====================================
//親コンポーネント import React, { useState } from 'react' type Props { texts: ItemList[] } interface ItemList { id: number text: string } // inputFormに文字を入力しているとき (TextInput(子)に渡したい) const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { setInputTitle(e.target.value) const App: React.FC = () => { const [text, setText] = useState('') const [ count, setcount ] = useState(0) return ( <div> <TextInput ={setText} handleInputCchange={handleInputCchange} /> </div> ) }
子コンポーネント import React, from 'react' interface Props { text: string handleInputCchange: React.ChangeEvent<HTMLInputElement> } const TextInput: React.FC<Props> = (props) => { } return ( <div> <div className="inputForm"> <div className="inner"> <input type="text" className="input" value={props.text} onChange={props.handleInputChange} /> </div> </div> </div> ) } export default TextInput
またいろんなサイトでみてみると coustractor (Props)
でと書いているサイトが多いですが書かなければいけないものなのでしょうか?
書く書かないだと何が違うのでしょうか?
// 子コンポーネント import React, { Component } from 'react'; class Modal extends Component { constructor(props){ super(props) } render() { return ( { this.props.[親で指定したstate名(A)] } <button onClick={ () => this.props.[親で指定したメソッド名(B)]() }>hoge</button> ); } }