У меня есть кнопка, к которой прикреплен handleClick
, и при нажатии ее предполагается добавить к одному из моих хуков состояния, она делает, но при втором щелчке:
Вот обработчик:
function handleClick(e, timeOfDayAndHour) {
e.persist();
setTextValueContainer((textValueContainer) => [
...textValueContainer,
textValue,
]);
console.log('textValue ', textValueContainer);
setDayInfoInChild({
...dayInfoInChild,
[currentDate]: {
[timeOfDayAndHour]: {
message: textValueContainer,
},
},
});
}
А вот разметка (внутри функции карты):
<code>return (
<>
{console.log('dayInfoInChild', dayInfoInChild)}
{/* {console.log('currentDate ', dayInfoInChild[currentDate])} */}
<h1>{dayInfo}</h1>
<Table celled structured>
<Table.Body>
{Array.from(Array(amountOfRows)).map((row, index) => {
return (
<React.Fragment key={index}>
<Table.Row>
<Table.Cell rowSpan="2" style={tableStyle}>
{TimeOfDaySetter(index)}
</Table.Cell>
<Table.Cell style={tableStyle}>
{
<strong>
{setExactHourHelper(index)}
:00
</strong>
}
<Message>
<Message.Header>Form data:</Message.Header>
</Message>
<TextArea
rows={2}
name="textarea"
onChange={(e) => handleChange(e)}
placeholder="Tell us more"
/>
<Button
fluid
attached="bottom"
content="submit"
onClick={(e) =>
handleClick(
e,
`${setExactHourHelper(index)}-${
index < 12 ? 'AM' : 'PM'
}`
)
}
/>
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell style={(tableStyle, colorOveride)}>
{
<strong>
{setExactHourHelper(index)}
:30
</strong>
}
<Message>
<Message.Header>Form data:</Message.Header>
<pre>
handleChange (e)} placeholder = "Расскажите подробнее" /> <Кнопка флюида прикреплена = "bottom" content = "submit" onClick = {handleClick} // onKeyPress = {this.handleKeyPress} /> < /Table.Row> ); })} </>);
Я думал, что добавление useEffect
поможет, но безрезультатно:
useEffect(() => {
window.addEventListener('onclick', handleClick);
return () => {
window.removeEventListener('onclick', handleClick);
};
}, []);
Это общий компонент:
<code>import { Button, Header, Message, Table, TextArea } from 'semantic-ui-react';
import React, { useState, useEffect } from 'react';
export default function Day({ dayInfo }) {
var [dayInfoInChild, setDayInfoInChild] = useState({});
var [currentDate, setCurrentDate] = useState('');
var [amountOfRows, setAmountOfRows] = useState(24);
var [textValue, setTextValue] = useState('');
var [timeOfDay, setTimeOfDay] = useState('');
var [textValueContainer, setTextValueContainer] = useState([]);
function handleChange(e) {
e.persist();
setTextValue(e.target.value);
console.log('textValueContainer ', textValueContainer);
console.log('textValue ', textValue);
}
function handleClick(e, timeOfDayAndHour) {
e.persist();
setTextValueContainer((textValueContainer) => [
...textValueContainer,
textValue,
]);
console.log('textValue ', textValueContainer);
setDayInfoInChild({
...dayInfoInChild,
[currentDate]: {
[timeOfDayAndHour]: {
message: textValueContainer,
},
},
});
}
function setExactHourHelper(index) {
return index === 0 ? 12 : '' || index > 12 ? index - 12 : index;
}
function TimeOfDaySetter(index) {
if (index === 0) {
return <Header as="h1">AM</Header>;
} else if (index === 12) {
// setTimeOfDay('PM');
return <Header as="h1">PM</Header>;
}
}
useEffect(() => {
if (dayInfo !== null) {
var modifiedDayInfo = dayInfo
.split(' ')
.map((item) => {
if (item.indexOf(',')) return item.replace(/,/g, '');
})
.join('-');
setCurrentDate(modifiedDayInfo);
if (localStorage.getItem(modifiedDayInfo)) {
var stringVersionOfModifiedDayInfo = modifiedDayInfo;
modifiedDayInfo = JSON.parse(localStorage.getItem(modifiedDayInfo));
if (!dayInfoInChild.hasOwnProperty(stringVersionOfModifiedDayInfo)) {
setDayInfoInChild({
...dayInfoInChild,
[stringVersionOfModifiedDayInfo]: modifiedDayInfo,
});
}
// console.log('dayInfoInChild', dayInfoInChild);
// console.log(
// 'stringVersionOfModifiedDayInfo',
// stringVersionOfModifiedDayInfo
// );
} else {
localStorage.setItem(modifiedDayInfo, JSON.stringify({}));
}
}
}, [dayInfo]);
useEffect(() => {
window.addEventListener('onclick', handleClick);
return () => {
window.removeEventListener('onclick', handleClick);
};
}, []);
const tableStyle = {
borderLeft: 0,
borderRight: 0,
};
const colorOveride = {
color: '#C1BDBD',
};
return (
<>
{console.log('dayInfoInChild', dayInfoInChild)}
{/* {console.log('currentDate ', dayInfoInChild[currentDate])} */}
<h1>{dayInfo}</h1>
<Table celled structured>
<Table.Body>
{Array.from(Array(amountOfRows)).map((row, index) => {
return (
<React.Fragment key={index}>
<Table.Row>
<Table.Cell rowSpan="2" style={tableStyle}>
{TimeOfDaySetter(index)}
</Table.Cell>
<Table.Cell style={tableStyle}>
{
<strong>
{setExactHourHelper(index)}
:00
</strong>
}
<Message>
<Message.Header>Form data:</Message.Header>
</Message>
<TextArea
rows={2}
name="textarea"
onChange={(e) => handleChange(e)}
placeholder="Tell us more"
/>
<Button
fluid
attached="bottom"
content="submit"
onClick={(e) =>
handleClick(
e,
`${setExactHourHelper(index)}-${
index < 12 ? 'AM' : 'PM'
}`
)
}
/>
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell style={(tableStyle, colorOveride)}>
{
<strong>
{setExactHourHelper(index)}
:30
</strong>
}
<Message>
<Message.Header>Form data:</Message.Header>
<pre>
<строки TextArea = {2} name = "textarea" onChange = {(e) => handleChange (e)} placeholder = "Расскажите подробнее" /> <Кнопка флюида прикреплена = "bottom" content = "submit" onClick = {handleClick} // onKeyPress = {this.handleKeyPress} /> ); })} </>); }
Итак, мой вопрос: почему он работает, но только на втором щелчке и как мне заставить его работать как положено?