Comment vérifier si chaque état a une valeur puis combiner toutes les valeurs?
<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="app"></div>
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
inputvalue : '',
allval: ''
}
}
onChangeOfInput =(name,value) =>{
this.setState({
[name]: value
});
}
getValues = () =>{
console.log(this.state);
if(this.state.Title1) {
this.setState({
allval: this.state.allval+this.state.Title1
});
}
}
render() {
return (
<div className="hello">
<Input onChangeOfInput={this.onChangeOfInput}
placeholder="Title 1" name="Title1" />
<br/>
<Input placeholder="Title 2" name="Title2" onChangeOfInput={this.onChangeOfInput} />
<br/>
<Input placeholder="Title 3" name="Title3" onChangeOfInput={this.onChangeOfInput}/>
<br/>
<Input placeholder="Title 4" name="Title4" onChangeOfInput={this.onChangeOfInput}/>
<br/>
<button onClick={this.getValues}>Get value</button>
</div>
)
}
}
class Input extends React.Component {
constructor(props) {
super(props)
this.state = {
inputvalue: ''
}
}
handleChange(e) {
this.setState({
inputvalue: e.target.value
});
this.props.onChangeOfInput(this.props.name,e.target.value)
}
render() {
return (
<input
type="text"
placeholder={this.props.placeholder}
value={this.state.inputvalue}
onChange={this.handleChange.bind(this)}
/>
)
}
}
ReactDOM.render(<App />, document.querySelector("#app"))
jsfiddle: https://jsfiddle.net/vxm2ojLz/
Le problème est là, je dois vérifier chaque valeur state.Title1 , state.Title2 , state.Title3 , state.Title4 s'ils ne sont pas vides, alors je veux combiner toutes les valeurs si ce n'est pas vide et attribuer les valeurs combinées à allVal , comment combiner toutes les valeurs à allval ? Merci
4 Réponses :
Vous devez faire quelque chose comme ceci.
getValues = () => {
console.log(this.state);
let combinedString = "";
Object.keys(this.state)
.map( igKey => {
if(this.state[igKey] != "" && igKey.includes('Title')){
combinedString = combinedString +''+ this.state[igKey];
return combinedString
}
});
this.setState({allval:combinedString})
console.log(combinedString);
}
violon de travail https: //jsfiddle.net/2nhc6drm/
espérons que cela vous aidera!
Merci pour la réponse! Cependant, chaque fois que je passe à une nouvelle valeur, le résultat est attaché à l'ancienne valeur à la nouvelle valeur.
C'est parce que l'état allval est lié dans CombinéString, pour cela, vous devez vérifier la clé comme ci-dessous: stackblitz.com/edit / react-4qakbb
Merci, @jayvel a édité ma réponse, cela m'a aidé à améliorer ma réponse.
Essayez de gérer getValues comme ceci:
getValues = () =>{
console.log(this.state);
let result = [];
Object.keys(this.state).forEach(key => {
if (key.includes('Title') && this.state[key]) result.push(`${key}: ${this.state[key]}`);
})
this.setState({
allval: result.join('; ')
})
}
Veuillez mettre à jour la méthode getValues : -
Pour la concatination, elle ignorera les clés allval et inputval .
getValues = () => {
let allval = ''
for(let key of Object.keys(this.state)){
if(key==='allval' || key==='inputval'){
continue;
}
else{
let value=this.state[key];
console.log(value);
if(value===''){
}
else{
allval=allval+value;
}
console.log(allval);
}
}
this.setState({allval:allval})
}
SandBox fonctionnant: - https://codesandbox.io / s / vqoxo9w1wy
J'espère que cela vous aidera,
Bravo !!
Je recommande d'utiliser reduction pour combiner les valeurs, et d'utiliser le setState fonctionnel pour éviter le double changement d'état:
<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>
class App extends React.Component {
state = {
allVal: '',
title1: '',
title2: ''
}
getValues = (prevState, name, newVal) => {
return Object.keys(prevState)
.reduce((acc, key) => {
if (key === 'allVal') return acc;
if (key === name) return acc + newVal;
return acc + prevState[key];
}, '')
}
handleChange = ({ target: { name, value } }) => {
this.setState(prevState => ({
[name]: value,
allVal: this.getValues(prevState, name, value)
}))
}
render(){
const { title1, title2, allVal } = this.state;
return (
<div>
<input name="title1" onChange={this.handleChange} value={title1} /><br />
<input name="title2" onChange={this.handleChange} value={title2} /><br />
allVal: <span>{allVal}</span>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));