我在 React 组件的输入中添加值时遇到问题。我想将生成的密码作为值放入输入中。目前密码未定义。
App.js - 主要 React 组件
class App extends React.Component {
state = {
passwordValue: "start",
rangeValue: 6
};
generatePassword = event => {
event.preventDefault();
var length = 8,
charset =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retPass = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retPass += charset.charAt(Math.floor(Math.random() * n));
}
console.log(retPass);
this.setState({ passwordValue: retPass });
return retPass;
};
render() {
return (
<div className={styles.container}>
<Header name="lock" />
<Generator
submitFn={this.generatePassword}
password={this.state.passwordValue} //props necessary for an input
/>
<Footer />
</div>
);
}
}
Generator.js - App.js 中使用的 React 组件
const Generator = ({ submitFn, props }) => {
return (
<form className={styles.generatContainer}>
//some form inputs
<button className={styles.generatContainer__button} onClick={submitFn}>
Generate Password
</button>
<div className={styles.generatContainer__input}>
<label name="newPass">Your New Password:</label>
<input type="text" value={props.password}></input> //here is a problem
</div>
</form>
);
};
export default Generator;
最佳答案
您没有解构密码
:
const Generator = ({ submitFn, password }) => {
// ...
<input type="text" value={password}></input> //here is a problem
}
或者:
const Generator = ({ submitFn, ...props }) => {
// ...
<input type="text" value={props.password}></input> //here is a problem
}
关于javascript - 在输入中添加值 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60192946/