如何在 React 无状态组件中编写和访问函数
How to write and access function in React stateless components
我想使用无状态 React 组件以 CSS 风格编写和访问 function/const。
我做了以下实现,但无法成功:
const MyComponent = ({ title, data }: Props) => {
function setPercentageColor() {
console.log("standard");
return "#ca2626";
}
const percentage = "50";
return (
<div className="progress-circle">
<CircularProgressbar
percentage={percentage}
text={percentage}
styles={{
root: {},
path: {
stroke: "#0080a6",
strokeWidth: "8",
transition: "stroke-dashoffset 0.5s ease 0s"
},
trail: {
stroke: setPercentageColor //here I want to access
},
text: {
fill: "#28323c",
fontSize: "35px",
fontFamily: "Roboto Regular"
}
}}
/>
</div>
);
};
export default MyComponent;
请帮忙写出正确的解决方案。
谢谢
您可以通过调用直接访问您的函数。即:
stroke: setPercentageColor()
这是一个简单的工作示例:
const App = () => {
const setTextColor = () => "#ca2626";
return (
<div>
<Foo
styles={{ colors: { text: setTextColor(), background: "black" } }}
/>
</div>
);
};
const Foo = (props) => {
const { styles } = props;
return (
<div
style={{
color: styles.colors.text,
backgroundColor: styles.colors.background,
}}
>
Foo
</div>
);
};
ReactDOM.render(
<App />,
document.getElementById("root")
);
<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>
我想使用无状态 React 组件以 CSS 风格编写和访问 function/const。
我做了以下实现,但无法成功:
const MyComponent = ({ title, data }: Props) => {
function setPercentageColor() {
console.log("standard");
return "#ca2626";
}
const percentage = "50";
return (
<div className="progress-circle">
<CircularProgressbar
percentage={percentage}
text={percentage}
styles={{
root: {},
path: {
stroke: "#0080a6",
strokeWidth: "8",
transition: "stroke-dashoffset 0.5s ease 0s"
},
trail: {
stroke: setPercentageColor //here I want to access
},
text: {
fill: "#28323c",
fontSize: "35px",
fontFamily: "Roboto Regular"
}
}}
/>
</div>
);
};
export default MyComponent;
请帮忙写出正确的解决方案。
谢谢
您可以通过调用直接访问您的函数。即:
stroke: setPercentageColor()
这是一个简单的工作示例:
const App = () => {
const setTextColor = () => "#ca2626";
return (
<div>
<Foo
styles={{ colors: { text: setTextColor(), background: "black" } }}
/>
</div>
);
};
const Foo = (props) => {
const { styles } = props;
return (
<div
style={{
color: styles.colors.text,
backgroundColor: styles.colors.background,
}}
>
Foo
</div>
);
};
ReactDOM.render(
<App />,
document.getElementById("root")
);
<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>