[英]React: Passing props to function components
我有一個關於道具和功能組件的看似微不足道的問題。 基本上,我有一個容器組件,它在用戶單擊按鈕觸發的狀態更改時呈現模態組件。 modal 是一個無狀態的函數組件,它包含一些需要連接到容器組件內的函數的輸入字段。
我的問題:當用戶與無狀態模態組件內的表單字段交互時,如何使用父組件內的函數來更改狀態? 我是否錯誤地傳遞了道具? 提前致謝。
容器
export default class LookupForm extends Component {
constructor(props) {
super(props);
this.state = {
showModal: false
};
}
render() {
let close = () => this.setState({ showModal: false });
return (
... // other JSX syntax
<CreateProfile fields={this.props} show={this.state.showModal} onHide={close} />
);
}
firstNameChange(e) {
Actions.firstNameChange(e.target.value);
}
};
功能(模態)組件
const CreateProfile = ({ fields }) => {
console.log(fields);
return (
... // other JSX syntax
<Modal.Body>
<Panel>
<div className="entry-form">
<FormGroup>
<ControlLabel>First Name</ControlLabel>
<FormControl type="text"
onChange={fields.firstNameChange} placeholder="Jane"
/>
</FormGroup>
);
};
示例:假設我想從 Modal 組件中調用this.firstNameChange
。 我猜想將 props 傳遞給函數組件的“解構”語法讓我有點困惑。 IE:
const SomeComponent = ({ someProps }) = > { // ... };
您需要為需要調用的每個函數單獨傳遞每個道具
<CreateProfile
onFirstNameChange={this.firstNameChange}
onHide={close}
show={this.state.showModal}
/>
然后在 CreateProfile 組件中你可以做
const CreateProfile = ({onFirstNameChange, onHide, show }) => {...}
通過解構,它將匹配的屬性名稱/值分配給傳入的變量。 名稱只需要與屬性匹配
或者只是做
const CreateProfile = (props) => {...}
並在每個地方調用props.onHide
或您嘗試訪問的任何道具。
我正在使用反應功能組件
在父組件中首先傳遞如下所示的道具
import React, { useState } from 'react';
import './App.css';
import Todo from './components/Todo'
function App() {
const [todos, setTodos] = useState([
{
id: 1,
title: 'This is first list'
},
{
id: 2,
title: 'This is second list'
},
{
id: 3,
title: 'This is third list'
},
]);
return (
<div className="App">
<h1></h1>
<Todo todos={todos}/> //This is how i'm passing props in parent component
</div>
);
}
export default App;
然后使用子組件中的道具,如下所示
function Todo(props) {
return (
<div>
{props.todos.map(todo => { // using props in child component and looping
return (
<h1>{todo.title}</h1>
)
})}
</div>
);
}
對上述答案的補充。
如果React
抱怨您傳遞的任何props
undefined
,那么您將需要使用default
值解構這些道具(常見於傳遞函數、數組或對象字面量),例如
const CreateProfile = ({
// defined as a default function
onFirstNameChange = f => f,
onHide,
// set default as `false` since it's the passed value
show = false
}) => {...}
只需在源組件上執行此操作
<MyDocument selectedQuestionData = {this.state.selectedQuestionAnswer} />
然后在目標組件上執行此操作
const MyDocument = (props) => (
console.log(props.selectedQuestionData)
);
finalfreq 答案的變體
如果你真的想要,你可以單獨傳遞一些道具和所有父道具(不推薦,但有時很方便)
<CreateProfile
{...this.props}
show={this.state.showModal}
/>
然后在 CreateProfile 組件中你可以做
const CreateProfile = (props) => {
並單獨銷毀道具
const {onFirstNameChange, onHide, show }=props;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.