我是React的新手,想知道我是否采取了正确的方法。
我有一个名为<App />
的个人资料页面和一个名为<ContactDetails />
的低级别组件。我想在<ContactDetails />
上存储<App />
的状态,所以我只需要在一个地方为所有组件编写AJAX逻辑。这种想法是否正确?
更具体地说,我感兴趣的是当用户更改输入时我将event.target.value
传递给<App />
的方式是否正确?
ContactDetails:
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: 'a@a.com',
firstName: ''
}
}
}
render() {
return (
<ContactDetails
onContactDetailsChange={contactDetails => this.setState({ contactDetails })}
contactDetails={this.state.contactDetails}
/>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'));
答案 0 :(得分:3)
这就是我编写解决方案的方式:
import React from 'react';
// Class based component handles the logic
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
contactDetails: {
email: 'a@a.com',
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.