使用钩子将类组件转换为函数式组件



我正试图将其转换为使用钩子的功能组件,但没有运气。我该怎么做呢?(对钩子不熟悉)。我已经尝试遵循文档,但我一定不是理解它。这应该以同样的方式工作,但使用钩子的功能组件。

import React, { Component } from "react";
const texts = [
['Text 1', 'blah', 'sdklfj'],
['Text 2', 'blah', 'sdklfj'],
['Text 3', 'blah', 'sdklfj'],
['Text 4', 'blah', 'sdklfj'],
];

export default class Testing extends Component {
constructor(props) {
super(props);
this.state = {
clickedText: [],
};
}
handleClick = (i) => {
this.setState({ clickedText: texts[i] });
};
render() {
const { clickedText } = this.state;
return (
<div>
{texts.map((text, i) => (
<button key={i} onClick={() => this.handleClick(i)}>
Click me {i + 1}
</button>
))}
{clickedText.length > 0 && <p>I clicked on button with text:</p>}
<ul>
{clickedText.map((t, i) => (
<li key={`text-${i}`}>{t}</li>
))}
</ul>
</div>
);
}
}
import React, { useState } from 'react';
const texts = [
['Text 1', 'blah', 'sdklfj'],
['Text 2', 'blah', 'sdklfj'],
['Text 3', 'blah', 'sdklfj'],
['Text 4', 'blah', 'sdklfj'],
];
const Testing = (props) => {
// useState is the function component equivalent of the inherited 'setState'
const [clickedText, setClickedText] = useState([]);
const handleClick = (i) => {
setClickedText(texts[i]);
};
return (
<div>
{texts.map((text, i) => (
<button key={i} onClick={() => handleClick(i)}>
Click me {i + 1}
</button>
))}
{clickedText.length > 0 && <p>I clicked on button with text:</p>}
<ul>
{clickedText.map((t, i) => (
<li key={`text-${i}`}>{t}</li>
))}
</ul>
</div>
);
};
export default Testing;

首先,您需要将类组件中的当前状态替换为功能组件的useState特性。还请阅读react的文档,了解如何在功能组件中使用状态。沙箱

import React, { useState } from "react";
const texts = [
["Text 1", "blah", "sdklfj"],
["Text 2", "blah", "sdklfj"],
["Text 3", "blah", "sdklfj"],
["Text 4", "blah", "sdklfj"]
];
const Testing = (props) => {
const [clickedText, setClickedText] = useState([]);
const handleClick = (i) => {
setClickedText(texts[i]);
};
return (
<div>
{texts.map((text, i) => (
<button key={i} onClick={() => handleClick(i)}>
Click me {i + 1}
</button>
))}
{clickedText.length > 0 && <p>I clicked on button with text:</p>}
<ul>
{clickedText.map((t, i) => (
<li key={`text-${i}`}>{t}</li>
))}
</ul>
</div>
);
};
export default Testing;

学习如何使用useState, useRef, useEffect。在你的例子中,你不需要useEffect,但你会用到它。

下面是你的钩子代码:
import { useRef, useState } from "react";
import "./styles.css";
export default function App() {
const [clickedText, setClickedText] = useState([]);
const texts = useRef([
["Text 1", "blah", "sdklfj"],
["Text 2", "blah", "sdklfj"],
["Text 3", "blah", "sdklfj"],
["Text 4", "blah", "sdklfj"]
]);
const handleClick = (i) => {
setClickedText(texts.current[i]);
};
return (
<div>
{texts.current.map((text, i) => (
<button key={i} onClick={() => handleClick(i)}>
Click me {i + 1}
</button>
))}
{clickedText.length > 0 && <p>I clicked on button with text:</p>}
<ul>
{clickedText.map((t, i) => (
<li key={`text-${i}`}>{t}</li>
))}
</ul>
</div>
);
}

https://codesandbox.io/s/hidden-waterfall-s0t0m?file=/src/App.js

相关内容

  • 没有找到相关文章

最新更新