我正在尝试使用reactjs将复选框的一个单击将一个输入框的值复制到另一个输入框。
这是我关于如何将输入值复制到另一个输入的代码。
import React from "react";
import "./styles.css";
export default class App extends React.Component {
constructor() {
super(props);
this.state = {
BillingAddress: "",
ShippingAddress: "",
copybilling: false
};
}
changeDetails = e => {
const { name, value, checked, maxLength } = e.target;
const { Details, formErrors } = this.state;
let formObj = {};
if (name === "copybilling") {
// handle the change event of language field
if (checked) {
// push selected value in list
formObj = {
...Details,
[name]: true
};
this.setState({
ShippingAddress: this.state.Details.BillingAddress
});
} else {
// remove unchecked value from the list
formObj = {
...Details,
[name]: false
};
}
} else {
// handle change event except language field
formObj = {
...Details,
[name]: value
};
}
};
render() {
return (
<>
<textarea
name="BillingAddress"
value={this.state.BillingAddress}
onChange={this.changeDetails}
/>
<textarea
name="ShippingAddress"
value={this.state.ShippingAddress}
onChange={this.changeDetails}
/>
</>
);
}
}
答案 0 :(得分:0)
我希望这会有所帮助
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
BillingAddress: "",
ShippingAddress: "",
copybilling: false
};
}
changeDetails = e => {
const { name, value, checked, maxLength } = e.target;
const { Details, formErrors } = this.state;
let formObj = {};
if (name === "copybilling") {
// handle the change event of language field
if (checked) {
// push selected value in list
this.setState({
[name]: true,
ShippingAddress: this.state.BillingAddress
});
} else {
// remove unchecked value from the list
this.setState({
[name]: false,
ShippingAddress: ''
});
}
} else {
// handle change event except language field
this.setState({
[name]: value
});
}
};
render() {
return (
<div>
<textarea
name="BillingAddress"
value={this.state.BillingAddress}
onChange={this.changeDetails}
/>
<textarea
name="ShippingAddress"
value={this.state.ShippingAddress}
onChange={this.changeDetails}
/>
Copy :
<input
type="checkbox"
name="copybilling"
checked={this.state.copybilling}
onChange={this.changeDetails}
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>