我正在从这个频道学习React 。最近,我从这里偶然发现了React Hooks 。因此,我试图将基于类的组件转换为基于钩子的组件。这是我基于类的组件:
import React, { Component } from 'react';
class AddNinja extends Component {
state = {
name: null,
age: null,
skill: null,
}
handleChange = e => {
this.setState({
[e.target.id]: e.target.value,
})
}
handleSubmit = e => {
e.preventDefault();
this.props.addNinja(this.state);
}
render() {
return (
<div>
<form onSubmit={ this.handleSubmit }>
<label htmlFor="name">Name: </label>
<input type="text" id="name" onChange={ this.handleChange } />
<label htmlFor="age">Age: </label>
<input type="number" id="age" onChange={ this.handleChange } />
<label htmlFor="skill">Skill: </label> …Run Code Online (Sandbox Code Playgroud)我有一个反应应用程序,其中 console.log 不显示其中的值,但显示消息。例如,
class Sample extends Component {
constructor() {
super()
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
msg:"Hi"
}}
handleSubmit(event) {
console.log("Message",this.state.msg);
}
render() {
return(
<div >
<RaisedButton label="Save" onClick={this.handleSubmit}/>
</div>
);
}}
Run Code Online (Sandbox Code Playgroud)
不仅是状态值,而且我给出的任何值都不会显示。会出现什么问题呢?请帮忙
我的应用程序组件如下所示:
class App extends Component {
clickHandler = () => {
console.log('click');
}
render() {
return (
<div className="App">
<div onClick={this.clickHandler}>Test1</div>
<Person onClick={this.clickHandler}>Test2</Person>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 Person 组件:
class Person extends Component {
render() {
return (
<div>{this.props.children}</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
当我单击Test1onClick 时有效并在控制台上显示单击,但当我单击Test2onClick 时不起作用。如何在父组件中处理 onClick?我不想将 onClick 传递给子组件。
我有一个名为filterContactsByValue. 它被柯里化并接受一个值和一个联系人列表,然后根据该值过滤列表并返回(新的)过滤列表。
由于列表通常很大(10.000 多个条目),Web 应用程序应该在智能手机上运行并且过滤器考虑了许多值,我想优化计算资源。因此,我过去useDebounce不会进行不必要的计算。
我也用useCallback这样来记住计算filteredContacts:
function FilteredContacts({contacts}) {
const [filterParam, setFilterParam] = useState('');
const [value] = useDebounce(filterParam, 800);
const filterContacts = filterContactsByValue(value.toLowerCase());
// Is this okay? ...
const getFilteredContacts = useCallback(() => filterContacts(contacts), [
value
]);
return (
<div className="main">
<SearchBar
value={filterParam}
onChangeText={setFilterParam}
/>
// ... and then this?
<ContactList contacts={getFilteredContacts()} />
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
我想知道这是否可以,或者返回这样的值是否是不好的做法。如果它很糟糕,为什么以及如何改进它?
编辑:
该filterContactsByValue功能:
import { any, filter, includes, map, pick, pipe, toLower, values } …Run Code Online (Sandbox Code Playgroud) 我有以下反应类组件每 10 秒调用一次 API。它的作品没有问题。
class Alerts extends Component {
constructor() {
this.state = {
alerts: {},
}
}
componentDidMount() {
this.getAlerts()
this.timerId = setInterval(() => this.getAlerts(), 10000)
}
componentWillUnmount() {
clearInterval(this.timerId)
}
getAlerts() {
fetch(this.getEndpoint('api/alerts/all"))
.then(result => result.json())
.then(result => this.setState({ alerts: result }))
}
render() {
return (
<>
<ListAlerts alerts={this.state.alerts} />
</>
)
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试将其转换为反应功能组件。这是我迄今为止的尝试。
const Alerts = () => {
const [alerts, setAlerts] = useState([])
useEffect(() => {
getAlerts()
setInterval(() => getAlerts(), 10000)
}, [])
getAlerts() …Run Code Online (Sandbox Code Playgroud) reactjs react-native react-component react-context react-functional-component
我正在使用Jest和Enzyme进行 React 应用程序测试。
我的文件夹结构看起来像
/源
/__测试__
/关卡组件
/成分
/关卡组件
/小部件
OuterComp.js
import React, { Component } from 'react'
import ChenDropdown from '../Widgets/ChenDropdown'
class OuterComp extends Component {
render() {
return (
<div>
<ChenDropdown />
<ChenDropdown />
</div>
)
}
}
export default OuterComp
Run Code Online (Sandbox Code Playgroud)
ChenDropdown.js
import React, { Component } from 'react'
class ChenDropdown extends Component {
render() {
return <h1>test</h1>
}
}
export default ChenDropdown
Run Code Online (Sandbox Code Playgroud)
OuterComp.test.js
import Adapter from 'enzyme-adapter-react-16'
import Enzyme, { …Run Code Online (Sandbox Code Playgroud) 我正在尝试制作简单的日历。在我的日历中,我有日、日名、月和月名组件,我在主日历上访问它。初始加载时,它将显示当前月历。
现在,当我从月份名称组件中选择月份时,想要传递给月份组件,然后传递给日期组件以呈现日期。
我尝试使用回调功能,但它没有帮助我
整个反应组件在这里https://stackblitz.com/edit/react-ts-z2278r
Day component
import * as moment from 'moment'
import * as React from 'react'
import { showComponent } from '../../../../models'
import { MonthNames } from './'
import styles from './Calendar.module.scss'
interface IDatePickerMonthsProps {
changeMonthComponent: (showComponent: showComponent, monthNo: number) => void
}
interface IDatePickerMonthsState {
dateObject: moment.Moment,
monthNo?: number
}
export class DatePickerMonths extends React.Component<IDatePickerMonthsProps, IDatePickerMonthsState> {
constructor(props: IDatePickerMonthsProps) {
super(props)
this.state = {
dateObject: moment()
}
}
public render() {
const monthPicker =
<div className="datepicker-days"> …Run Code Online (Sandbox Code Playgroud) 我很好奇setState作为道具传递给孩子(哑组件)是否违反了任何“最佳实践”或会影响优化。
下面是一个例子,我有父容器的传球state和setState两个子组件,其中,子组件会调用该setState函数。
我没有明确调用setState孩子,他们引用一个服务来处理状态属性的正确设置。
export default function Dashboard() {
const [state, setState] = useState({
events: {},
filters: [],
allEvents: [],
historical: false,
});
return (
<Grid>
<Row>
<Col>
<EventsFilter
state={state}
setState={setState}
/>
<EventsTable
state={state}
setState={setState}
/>
</Col>
</Row>
</Grid>
)
}
Run Code Online (Sandbox Code Playgroud)
仪表板 setState 服务示例
function actions(setState) {
const set = setState;
return function () {
return ({
setEvents: (events) => set((prev) => ({
...prev,
events,
})),
setAllEvents: (allEvents) => set((prev) => …Run Code Online (Sandbox Code Playgroud) javascript reactjs react-component react-state-management react-hooks
“反应”:“^16.13.1”“反应转换组”:“^4.3.0”
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>
Run Code Online (Sandbox Code Playgroud)
嗨,大家好。
我遇到了 findDOMNode 警告,但在互联网上找不到正确的解决方案。
index.js:1 警告:在 StrictMode 中不推荐使用 findDOMNode。findDOMNode 传递了一个 Transition 实例,它在 StrictMode 内...
这个例子是我从off docs here复制的,点击按钮,出现了同样的错误。
const Toolbar = (props) => {
const [inProp, setInProp] = useState(false);
return (
<div>
<CSSTransition in={inProp} timeout={200} classNames="my-node">
<div>
{"I'll receive my-node-* classes"}
</div>
</CSSTransition>
<button type="button" onClick={() => setInProp(true)}>
Click to Enter
</button>
</div>
)
};
Run Code Online (Sandbox Code Playgroud)
来自互联网的解决方案建议尝试 createRef(我使用了 usePef 钩子),但是使用 Transitions,它不起作用。
似乎 React.StrictMode 会抛出这样的警告,直到这个库的补丁被合并,但仍然没有看到创建的问题
对于如何解决问题的任何帮助或建议,我将不胜感激
strict-mode reactjs deprecation-warning react-component react-ref
在 React 中,有一种简单的方法可以在多层组件中共享“信息”。这是通过使用上下文
import {UserCtx} from "./stores/UserCtx";
<UserCtx.Provider value={new user(info)}>
<SomeComponent />
</UserCtx.Provider/>
Run Code Online (Sandbox Code Playgroud)
然后在某个组件中:
import {UserCtx} from "./stores/UserCtx";
function SomeComponent() {
const userData = React.useContext(UserCtx);
return <div>JSON.stringify(userData)</div>
}
Run Code Online (Sandbox Code Playgroud)
然而,这要求上下文对象定义对于所有对象都是可见的。因此,当创建组件库时,它不能真正被使用吗?
假设上面的“示例”SomeComponent是一个库组件,我如何将主应用程序的上下文共享给该组件?通过添加属性来共享似乎有些牵强,在这一点上我不妨直接提供用户(或上下文存储的任何内容)?
react-component ×10
reactjs ×10
javascript ×4
react-hooks ×3
enzyme ×1
jestjs ×1
momentjs ×1
react-native ×1
react-ref ×1
strict-mode ×1