我是React的新手,想知道我是否在这里采取了正确的方法。
我有一个名为<App />
的配置文件页面和一个名为<ContactDetails />
的较低级组件。我想将<ContactDetails />
的状态存储在<App />
上,所以我只需要在一个位置为所有组件编写AJAX逻辑。这种想法正确吗?
更具体地说,我对用户更改输入时将event.target.value
传递给<App />
的方式是否正确感兴趣?
联系方式:
import React from 'react';
class ContactDetails extends React.Component {
render() {
return (
<div>
<input value={this.props.contactDetails.email} onChange={event => this.props.onContactDetailsChange(Object.assign(this.props.contactDetails, {email: event.target.value}))} />
<input value={this.props.contactDetails.firstName} onChange={event => this.props.onContactDetailsChange(Object.assign(this.props.contactDetails, {firstName: event.target.value}))} />
</div>
)
}
}
export default ContactDetails;
应用程式:
import React from 'react';
import ReactDOM from 'react-dom';
import ContactDetails from './components/contact_details';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
contactDetails: {
email: '[email protected]',
firstName: ''
}
}
}
render() {
return (
<ContactDetails
onContactDetailsChange={contactDetails => this.setState({ contactDetails })}
contactDetails={this.state.contactDetails}
/>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'));
最佳答案
这就是我写您的解决方案的方式:
import React from 'react';
// Class based component handles the logic
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
contactDetails: {
email: '[email protected]',
firstName: '',
lastName: '',
mobile: ''
}
}
}
// One function to handle input changes
handleContactDetailsChange = (value) => {
// Object.assign() first argument is the target object.
// Object.assign() returns the target object into contactDetails.
// Second argument are the old contactDetails.
// Third argument is the new input value.
// Because the third argument comes later it overwrites anything from
// contactDetails that has the same key.
this.setState({
contactDetails: Object.assign({}, this.state.contactDetails, { ...value })
});
// { ...value } can also be written as just value, but this creates a copy.
}
render() {
return (
<ContactDetails
onContactDetailsChange={this.handleContactDetailsChange}
contactDetails={this.state.contactDetails}/>
);
}
}
// Stateless functional component.
// Takes props as an argument.
const ContactDetails = (props) => {
// Pull of the two props we need from the props object(cleaner syntax).
const { onContactDetailsChange, contactDetails } = props;
return (
<div>
<input
value={contactDetails.email}
onChange={event => onContactDetailsChange({ email: event.target.value })}
/>
<input
value={contactDetails.firstName}
onChange={event => onContactDetailsChange({ firstName: event.target.value })}
/>
</div>
)
};
export default App;
ContactDetails通常位于其自己的文件中。另外,由于目标是
Object.assign(this.props.contactDetails, {firstName: event.target.value})
,因此您可以通过调用this.props.contactDetails
修改道具。 The React philosophy is that props should be immutable and top-down.