textObj
является нулевым в методе рендеринга. Вы должны это использовать в componentDidMount()
. Затем создайте массив ref, в противном случае ссылка будет переопределена каждым элементом цикла.
export class Labels extends React.Component<Props> {
textRefs = new Array(React.createRef<SVGTextElement>())
componentDidMount() {
const { maxTextwidth } = this.props
this.textRefs.forEach((ref, i) => {
placeTextWithEllipsis(
this.textRefs[i].current,
this.textRefs[i].current.innerHTML,
maxTextwidth
)
})
}
render() {
return (
// ...
<text
ref={(this.textRefs[i] = React.createRef<SVGTextElement>())}
x={rectWidth - paddingLeftRight}
y={y + rectHeight / 2}
textAnchor="end"
alignmentBaseline="middle"
>
{...}
</text>
// ...
)
}
}
попробуйте следующее:
class MyObject {
public:
template <class T>
MyObject &operator<<(const T &x) {
s << ':' << x << ':';
return *this;
}
std::string to_string() const { return s.str(); }
private:
std::ostringstream s;
};
MyObject obj;
obj << "Hello" << 12345;
std::cout << obj.to_string() << std::endl;
Есть определенные вещи, которые вы не сможете добавить в поток, но это должно работать для всех основных операций.
Я бы применил немного другой подход и создал объект форматирования.
Затем объект форматирования будет обрабатывать вставку символа формата, когда он применяется к потоку.
#include <iostream>
template<typename T>
class Format
{
public:
Format(T const& d):m_data(d) {}
private:
template<typename Y>
friend std::ostream& operator<<(std::ostream& str,Format<Y> const& data);
T const& m_data;
};
template<typename T>
Format<T> make_Format(T const& data) {return Format<T>(data);}
template<typename T>
std::ostream& operator<<(std::ostream& str,Format<T> const& data)
{
str << ":" << data.m_data << ":";
}
int main()
{
std::cout << make_Format("Hello") << make_Format(123);
}
Вы можете найти ответы на Как мне создать собственный ostream / streambuf? полезно.